HttpClient and MultipartFormDataContent (portal) are minimum applicable. NET Framework version 4.5

Sender code

using (HttpClient client = new HttpClient()) { var content = new MultipartFormDataContent(); Add(new StringContent("123456"), "QQ "); string path = Path.Combine(System.Environment.CurrentDirectory, "1.png"); / / Add files parameters, called files, File called 123. The PNG content. the 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); }Copy the code

Receiver code

[HttpPost] public async Task<JsonResult> SaveFile([FromForm]string qq, IFormFile file) {return await task.run (() => {try {// save file to local 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(); }); }Copy the code

Note: If you want to receive data as a parameter, you need to make sure that the parameter name is the same as the name set in the send request above. Otherwise, the parameter cannot be automatically bound to the parameter and you need to mark the parameter with [FromForm].

Receive data using model objects

public class SaveFileModel
{
    public string qq { get; set; }
    public IFormFile File { get; set; }
}
public async Task<JsonResult> SaveFile([FromForm]SaveFileModel model)
{
    //......
}
Copy the code

Use HttpContext to get data from the requested Form

public async Task<JsonResult> SaveFile() { return await Task.Run(() => { var files = HttpContext.Request.Form.Files; var qq = HttpContext.Request.Form["qq"]; / /... }); }Copy the code

conclusion

This question is written in a. Net Core project, used to be. Net Framework 4.0 uses a string to concatenate the contents of a file in a form with boundary boundaries everywhere. The MultipartFormDataContent for form submission and uploading the file is the internal splice that helps us put together this complex content. (Use Fiddler to grab the request.)

Reproduced in:www.cnblogs.com/cplemom/p/1…

Thanks for sharing.