C# HttpClient以multipart/form-data形式 提交文件和其它参数


HttpClient和MultipartFormDataContent(传送门)最低适用于.NET Framework 4.5版本

 public async Task<WebApiResult> UploadFile(UploadFileModel info, IList<IFormFile> files)
        {
            try
            {
                var postContent = new MultipartFormDataContent();
                string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
                postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
                var requestUri = "/api/File/UploadFiles";
                if (files.Any())
                {
                    var stream = files[0].OpenReadStream();
                    //files为文件key, files[0].FileName 为文件名称
                    postContent.Add(new StreamContent(stream, (int)stream.Length), "files", files[0].FileName);
                    //Region为请求文件接口需要的参数,根据调用接口参数而定
                    postContent.Add(new StringContent(info.Region), "Region");

                }
                var response = await _httpclient.PostAsync(requestUri, postContent);
                if (response.IsSuccessStatusCode)
                {
                    var responseStr = await response.Content.ReadAsStringAsync();
                    var responseObj = JsonConvert.DeserializeObject<WebApiResult>(responseStr);
                    return responseObj;
                }
                //WebApiResult为自定义反会值
                return new WebApiResult(ApiResultCode.Fail, "保存失败");
            }
            catch (Exception ex)
            {
                throw new Exception("保存file异常");
            }

        }
发送端代码
using (HttpClient client = new HttpClient())
{
    var content = new MultipartFormDataContent();
    //添加字符串参数,参数名为qq
    content.Add(new StringContent("123456"), "qq");

    string path = Path.Combine(System.Environment.CurrentDirectory, "1.png");
    //添加文件参数,参数名为files,文件名为123.png
    content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "123.png");

    var requestUri = "http://192.168.1.108:56852/api/Test/SaveFile";
    var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;

    Console.WriteLine(result);
}
接收端代码
[HttpPost]
public async Task<JsonResult> SaveFile([FromForm]string qq, IFormFile file)
{
    return await Task.Run(() =>
    {
        try
        {
            //保存文件到本地
            var filefullPath = Path.Combine(Directory.GetCurrentDirectory(), file.FileName);
            using (FileStream fs = new FileStream(filefullPath, FileMode.Create))
            {
                file.CopyTo(fs);
                fs.Flush();
            }
        }
        catch (Exception ex)
        {
            return Fail(file.FileName + "---" + ex.Message);
        }
        return Success();
    });
}

C# HttpClient以multipart/form-data形式 提交文件和其它参数
https://www.cnblogs.com/personblog/p/12030987.html
https://www.cnblogs.com/cplemom/p/11264040.html
https://blog.csdn.net/qq_35106907/article/details/85260639

此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。

原文地址:https://www.cnblogs.com/shy1766IT/p/15421885.html