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