Tag Archives: c# Httpclient

C#: How to Use Httpclient to upload files with other parameters

Httpclient and multipartformdatacontent are at least suitable for. Net Framework version 4.5

Sender code

using (HttpClient client = new HttpClient())
{
  var content = new MultipartFormDataContent();
  //Add a string parameter named qq
  content.Add(new StringContent("123456"), "qq");
 
  string path = Path.Combine(System.Environment.CurrentDirectory, "1.png");
  //add a file parameter named files, the file name is 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);
}

Receiver code

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

Note: if you want to receive data in the form of parameters, you need to make sure that the parameter name is consistent with the name set in the sending request above. Otherwise, it cannot be automatically bound to the parameter, and you need to mark the parameter with [fromform].

Using model object to receive data

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

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"];
    //......
  });
}

Summary
this problem is encountered when writing a. Net core project. In the past, in. Net framework 4.0, string was used to splice the contents of files in the form, and there were boundary lines everywhere. Multipartformdatacontent is used for form submission. The upload file of C # tutorial helps us to splice this complex content. (you can grab the request with Fiddler) EMM I’ll find out how to upload the original file, and update this article if there is one.

The above is the details of C # using httpclient to upload files with other parameters