.NET 5(C#)通过HttpClient方式提交文件到服务器实现上传文件

本文主要介绍.NET 5中,通过HttpClient实现请求提交上传的文件到服务器的方法,以及相关的示例代码。

1、文件读写操作

using System;
using System.IO;
using System.Text;
class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MyTest.txt";
        try
        {
            // 创建文件,如果文件存在则覆盖该文件。
            using (FileStream fs = File.Create(path))
            {
                byte[] info = new UTF8Encoding(true).GetBytes("https://www.cjavapy.com");
                // 向文件添加一些信息。
                fs.Write(info, 0, info.Length);
            }
            // 打开流并读取它。
            using (StreamReader sr = File.OpenText(path))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
}

2、使用HttpClient实现请求提交上传的文件

static async Task Main(string[] args)
    {
        await TryUpload();
    }
    private const string Boundary = "EAD567A8E8524B2FAC2E0628ABB6DF6E";
    private static readonly HttpClient HttpClient = new()
    {
        BaseAddress = new Uri("https://localhost:5001/")
    };
    private static async Task TryUpload()
    {
        var requestContent = new MultipartFormDataContent(Boundary);
        requestContent.Headers.Remove("Content-Type");
        requestContent.Headers.TryAddWithoutValidation("Content-Type", $"multipart/form-data; boundary={Boundary}");
        var fileContent = await File.ReadAllBytesAsync(@"C:\\cjavapy.png");
        var byteArrayContent = new ByteArrayContent(fileContent);
        byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");
        requestContent.Add(byteArrayContent, "avatar", "Unbenannt.PNG");
        var postResponse = await HttpClient.PostAsync("/api/Image", requestContent);
    }

3、后台文件上传API

[Route("api/[controller]")]
[ApiController]
public class ImageController : ControllerBase
{
    // POST api/<ImageController>
    [HttpPost]
    public void Post([FromForm] UserModel info)
    { 
        var memoryStream = new MemoryStream();
        info.Avatar.CopyTo(memoryStream);
        var bytes = memoryStream.ToArray();
    }
}
public class UserModel
{
    [FromForm(Name = "avatar")]
    public IFormFile Avatar { get; set; }

    [FromForm(Name = "name")]
    public string Name { get; set; }
}

推荐阅读
cjavapy编程之路首页