首页 > 解决方案 > 如何使用 HttpClient 实现 WebClient.UploadFileAsync?

问题描述

我有以下功能

public bool UploadFirmware(string ipAddress)
        {
            Uri url = new Uri($"https://{ipAddress}/upload.html");
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string selectedFileName = openFileDialog1.FileName;
                if (selectedFileName == string.Empty)
                    return false;
                else
                {
                    using (var webClient = new WebClient())
                    {
                        webClient.UploadFileAsync(url, "POST", selectedFileName);
                        webClient.UploadFileCompleted += WebClient_UploadFileCompleted; 
                    }
                }
            }
            return false;
        }

此功能正常工作,它能够将文件上传到目的地。但是,我想用和 HttpClient 更改 WebClient,因为我想同时将文件上传到多个目的地,而不为每个请求创建一个新的 WebClient。我的 HttpClient 如下:

public async Task<bool> UploadFirmware(string[] ipAddresses)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string selectedFileName = openFileDialog1.FileName;
                if (selectedFileName == string.Empty)
                {
                    return false;
                }

                else
                {
                    var multiForm = new MultipartFormDataContent();
                    var array = File.ReadAllBytes(selectedFileName);
                    var fileContent = new ByteArrayContent(array);
                    fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                    multiForm.Add(fileContent, "files", Path.GetFileName(selectedFileName));
                    var url = $"https://{ipAddresses[0]}/upload.html";
                    var response = await httpClient.PostAsync(url, multiForm);
                    var test = response.Content;
                   
                    return true;
                   
                }
            }
            return false;
        }

在我当前的实现中,响应是 400,Bad request,这让我认为我还没有正确创建请求。我的要求是,如果你能指出我正确的方向,我做错了什么?需要 HttpClient 吗?创建多个 WebClient 可能不会造成问题。

PS:我发送的文件是 .fw 类型的,目前我正在尝试获得一个响应以通过。在我能够正确执行单个请求后,我将使用 Tasks。

标签: c#http

解决方案


推荐阅读