[英]Post request to download file of a webserver from a WPF App (C#)
在以下代码中,我可以向网络服务器发送 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();
但是如何取回文件呢?
发送文件通常是通过将内容作为二进制数据传输来完成的。 如果您不显式发送文本数据,则使用HttpClient.ReadAsString
是没有用的。 将响应内容读取为字节数组或 stream。
使用readfile() function 发送文件:
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.