C# File Upload with HttpClient FormData

Using FormData to upload files in C# can be achieved through the HttpClient class. Here is a simple example code:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (var client = new HttpClient())
        {
            using (var formData = new MultipartFormDataContent())
            {
                // 添加要上传的文件
                var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes("path/to/file"));
                fileContent.Headers.Add("Content-Type", "application/octet-stream");
                formData.Add(fileContent, "file", "filename.txt");

                // 发送POST请求
                var response = await client.PostAsync("http://example.com/upload", formData);

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("文件上传成功");
                }
                else
                {
                    Console.WriteLine("文件上传失败");
                }
            }
        }
    }
}

In the code above, a HttpClient object is first created, and a FormData object is created using MultipartFormDataContent. The content of the file to be uploaded is then read using ByteArrayContent and added to the FormData. Finally, the file is uploaded by sending a POST request using the PostAsync method.

It is important to note that, in actual usage, you need to replace “path/to/file” and “http://example.com/upload” with the specific file path and upload interface address.

bannerAds