简体   繁体   English

发布从 WPF 应用程序下载网络服务器文件的请求(C#)

[英]Post request to download file of a webserver from a WPF App (C#)

In the following code, I can send a POST request for the webserver and get a response:在以下代码中,我可以向网络服务器发送 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;
    }
}

Is there a way to get a file sending a POST request and then save this file in a specific folder in the user's computer?有没有办法获取发送 POST 请求的文件,然后将此文件保存在用户计算机的特定文件夹中?

(What would be the PHP code to return the file after receiving the user's credentials and how would I get this file in the C# code?) (收到用户凭据后返回文件的 PHP 代码是什么?如何在 C# 代码中获取此文件?)

For example:例如:

<?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;
}

And in the WPF App, in C# usually I would read the response like this:在 WPF 应用程序中,在 C# 中,我通常会读到这样的响应:

var response = await client.PostAsync("https://url...", content);
var responseString = await response.Content.ReadAsStringAsync();

But how would it be to get the file back?但是如何取回文件呢?

Sending files is generally done by transferring the content as binary data.发送文件通常是通过将内容作为二进制数据传输来完成的。 If you don't explicitly send text data, using HttpClient.ReadAsString is useless.如果您不显式发送文本数据,则使用HttpClient.ReadAsString是没有用的。 Either read the response content as byte array or as stream.将响应内容读取为字节数组或 stream。

Sending the file using the readfile() function:使用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;

There are alternatives eg, using cURL etc.还有其他选择,例如,使用 cURL 等。

To request and save the file on your C# client you can handle the response content directly as Stream or byte array:要在 C# 客户端上请求并保存文件,您可以将响应内容直接处理为Streambyte数组:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM