c# - 如何使用 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。
解决方案
推荐阅读
- javascript - 在 React Native App 中收到警告“列表中的每个孩子都应该有一个唯一的 key prop”
- cmake - cmake ADD_EXECUTABLE 无法设置“../bin/xxx”
- kdb - KDB:如何获取表中行的不同值?
- javascript - Javascript如何更改svg线性渐变停止颜色
- tensorflow - 调整图像大小时出错:TypeError:无法为
我正在尝试运行一个 Age CGAN 程序,作为其中的一部分,我需要将图像大小从 64x64x3 调整为 192x192x3。在调整大小时,由于某种原因,我收到错误消息
TypeError: Could not build a TypeSpec for <KerasTens
- bash - 在 bash 中,我想将文件名保存在列表中。有什么解决办法吗?
- c# - 使用实体框架代码迁移运行 EnsureScheme 会导致语法错误
- python - 如何在 Python 会话中打开带有重定向的登录页面?
- html - 将html特定表中句子的第一个单词大写
- spring - STS 中的调试错误