当前位置:首页 > 行业动态 > 正文

c#批量上传图片到服务器示例分享

C#批量上传图片到服务器示例分享:该示例展示了使用C#实现批量上传图片至服务器的过程,包括图片选择、上传进度显示及错误处理等关键步骤,为开发者提供了实用的参考代码和详细注释。

在C#中批量上传图片到服务器是一个常见的需求,特别是在需要处理大量图像数据的应用中,下面我将分享一个示例代码,展示如何使用C#实现这一功能。

示例代码

确保你已经安装了System.Net.Http命名空间,它提供了HTTP客户端功能。

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
    static async Task Main(string[] args)
    {
        // 图片文件路径数组
        string[] imagePaths = { "path/to/image1.jpg", "path/to/image2.jpg" };
        // 服务器上传URL
        string uploadUrl = "https://example.com/upload";
        // 调用批量上传方法
        await UploadImagesAsync(imagePaths, uploadUrl);
    }
    static async Task UploadImagesAsync(string[] imagePaths, string uploadUrl)
    {
        using (HttpClient client = new HttpClient())
        {
            foreach (var imagePath in imagePaths)
            {
                if (!File.Exists(imagePath))
                {
                    Console.WriteLine($"文件不存在: {imagePath}");
                    continue;
                }
                using (var fileStream = new FileStream(imagePath, FileMode.Open))
                {
                    MultipartFormDataContent form = new MultipartFormDataContent();
                    form.Add(new StreamContent(fileStream), "file", Path.GetFileName(imagePath), "image/jpeg");
                    HttpResponseMessage response = await client.PostAsync(uploadUrl, form);
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"上传成功: {imagePath}");
                    Console.WriteLine($"服务器响应: {responseBody}");
                }
            }
        }
    }
}

代码说明

Main方法:定义了要上传的图片路径数组和服务器的上传URL,然后调用UploadImagesAsync方法进行批量上传。

UploadImagesAsync方法:使用HttpClient类创建HTTP客户端,遍历每个图片文件路径,检查文件是否存在,然后创建MultipartFormDataContent对象,将文件流添加到表单数据中,最后通过POST请求将图片上传到服务器,并打印服务器的响应。

相关问答FAQs

Q1: 如果服务器要求身份验证怎么办?

A1: 可以在HttpClient实例中设置身份验证信息,如果服务器使用基本身份验证,可以这样设置:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password")));

Q2: 如何处理上传失败的情况?

A2: 可以在捕获异常时进行处理,例如记录日志或重试上传,修改后的代码如下:

static async Task UploadImagesAsync(string[] imagePaths, string uploadUrl)
{
    using (HttpClient client = new HttpClient())
    {
        foreach (var imagePath in imagePaths)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine($"文件不存在: {imagePath}");
                continue;
            }
            try
            {
                using (var fileStream = new FileStream(imagePath, FileMode.Open))
                {
                    MultipartFormDataContent form = new MultipartFormDataContent();
                    form.Add(new StreamContent(fileStream), "file", Path.GetFileName(imagePath), "image/jpeg");
                    HttpResponseMessage response = await client.PostAsync(uploadUrl, form);
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine($"上传成功: {imagePath}");
                    Console.WriteLine($"服务器响应: {responseBody}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"上传失败: {imagePath}, 错误: {ex.Message}");
            }
        }
    }
}

小编有话说

批量上传图片到服务器是很多应用中的常见需求,通过使用C#的HttpClient和MultipartFormDataContent类,可以方便地实现这一功能,在实际应用中,可能还需要考虑更多的细节,比如错误处理、进度显示、并发上传等,希望这个示例能对你有所帮助!

0