HttpClient 是微软在.NET Framework 4.5 引入的一个HTTP客户端库,命名空间为 System.Net.Http,目的是简化开发者对Http的调用。
下面演示使用HttpClient 实现多文件同时上传
class Program
{
private const string Url = "https://localhost:44312/api/Upload";
private static List<string> FilePath = new List<string>
{
@"C:\Users\xxx\Desktop\test\large (10) - 副本 - 副本.jpg",
@"C:\Users\xxx\Desktop\test\large (11) - 副本 - 副本.jpg"
};
static async Task Main(string[] args)
{
Console.WriteLine("开始上传?");
Console.ReadKey();
HttpClientHandler handler = new HttpClientHandler();
ProgressMessageHandler progressMessageHandler = new ProgressMessageHandler(handler);
progressMessageHandler.HttpSendProgress += ProgressMessageHandler_HttpSendProgress;
HttpClient httpClient = new HttpClient(progressMessageHandler);
using var multipartFormData = new MultipartFormDataContent();
foreach (var file in FilePath)
{
multipartFormData.Add(new ByteArrayContent(await File.ReadAllBytesAsync(file)), "files", file);
}
var response = await httpClient.PostAsync(Url, multipartFormData);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
Console.WriteLine(data);
}
}
private static void ProgressMessageHandler_HttpSendProgress(object sender, HttpProgressEventArgs e)
{
Console.WriteLine(e.ProgressPercentage+"%");
}
}
ProgressMessageHandler
是为了向调用者报告上传或者下载的进度。
注:要上传多文件multipartFormData
添加的HttpContent
的Name
要为files
,ASP.NET Core API 后端才能正常解析出IFormFIle
。
网友评论