在以下代碼中,我可以向網路服務器發送 POST 請求并獲得回應:
private static readonly HttpClient client = new HttpClient();
public async static Task<int> User(string email, string password)
{
email = email.ToLower();
string theEmail = Cryptor.Encrypt(email);
string thePass = Cryptor.Encrypt(password);
try
{
var values = new Dictionary<string, string>
{
{ "email", theEmail },
{ "password", thePass }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://url...", content);
var responseString = await response.Content.ReadAsStringAsync();
Globals.USER = JsonConvert.DeserializeObject<UserObject>(responseString);
return 1;
}
catch (Exception)
{
return 3;
}
}
有沒有辦法獲取發送 POST 請求的檔案,然后將此檔案保存在用戶計算機的特定檔案夾中?
(收到用戶憑據后回傳檔案的 PHP 代碼是什么,如何在 C# 代碼中獲取該檔案?)
例如:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
$email = $_POST['email'];
$password = $_POST['password'];
// Validate user
// .
// .
// .
// Until here it's ok
// Now what would be the code to return the file?
// For example, a file from the following path: "user-folder/docs/image.png"
}else{
echo 'error';
die;
}
在 WPF 應用程式中,在 C# 中,我通常會讀到這樣的回應:
var response = await client.PostAsync("https://url...", content);
var responseString = await response.Content.ReadAsStringAsync();
但是如何取回檔案呢?
uj5u.com熱心網友回復:
發送檔案通常是通過將內容作為二進制資料傳輸來完成的。如果您不明確發送文本資料,則使用HttpClient.ReadAsString是無用的。將回應內容作為位元組陣列或流讀取。
使用readfile()函式發送檔案:
$file = 'user-folder/docs/image.png';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' .filesize($file));
readfile($file);
exit;
還有其他選擇,例如使用 cURL 等。
要在 C# 客戶端上請求并保存檔案,您可以直接將回應內容處理為Stream陣列byte:
var response = await httpClient.PostAsync("https://url...", content);
var destinationFilePath = "image.png";
await using var destinationStream = File.Create(destinationFilePath);
// Handle the response directly as Stream
await using Stream sourceStream = await response.Content.ReadAsStreamAsync();
await sourceStream.CopyToAsync(destinationStream);
// Alternatively, create the Stream manually
// or write the byte array directly to the file
byte[] sourceData = await response.Content.ReadAsByteArrayAsync();
await destinationStream.WriteAsync(sourceData);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/410240.html
標籤:
上一篇:WPF網格列50%寬度
