用C#写一个使用httpclient上传多个图片
以下是使用C#和HttpClient上传多个图片的示例代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace UploadMultipleImages
{
class Program
{
static async Task Main(string[] args)
{
var images = new List<string> { "image1.jpg", "image2.png", "image3.gif" };
var apiUrl = "https://example.com/upload";
using (var httpClient = new HttpClient())
{
using (var formData = new MultipartFormDataContent())
{
foreach (var image in images)
{
var fileContent = new ByteArrayContent(File.ReadAllBytes(image));
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); // replace with actual image type
formData.Add(fileContent, "images", Path.GetFileName(image));
}
var response = await httpClient.PostAsync(apiUrl, formData);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Upload successful!");
}
else
{
Console.WriteLine("Upload failed!");
}
}
}
Console.ReadLine();
}
}
}
此代码将创建一个HttpClient实例,并使用MultipartFormDataContent创建一个包含多个文件的表单数据。然后,它将使用PostAsync方法将表单数据上传到指定的API端点。请注意,此示例假定所有图像都存储在与应用程序相同的目录中。您需要根据自己的需求更改文件路径和API端点
原文地址: https://www.cveoy.top/t/topic/hwLw 著作权归作者所有。请勿转载和采集!