C#使用HttpClient上传文件并附带其他参数
发送端代码
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(); }); }