Richard
Richard

Reputation: 1739

Posting a File to a Controller - IFormFiles are always empty

I'm trying to make a POST request that sends files to a controller method with the following definition

public async Task<ActionResult> PostUploadFilesAsync([BindRequired, FromForm] IEnumerable<IFormFile> files) 

But 'files' is always empty when it receives the request.

I've tried a few different ways of posting it, and this is my current attempt at building up the request. The files I'm sending have been uploaded to my own controller and seem fine at that point.

  var client = new HttpClient();
  var content = new MultipartFormDataContent();

  MemoryStream ms = new MemoryStream();
  await Request.Form.Files[0].CopyToAsync(ms);
  content.Add(new StreamContent(ms));
  var address = <the-address>;
  var result = client.PostAsync(address, content);

I can't figure out why the files are not being received. Thanks

Upvotes: 3

Views: 1228

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93273

I see two issues with the code you've posted:

  1. When calling Add on the MultipartFormDataContent instance, you need to specify both a name and a filename. The name parameter must match the parameter being used in PostUploadFilesAsync:

    content.Add(new StreamContent(ms), "files", "file1");
    

    You can do this multiple times, to add multiple files. For example:

    content.Add(new StreamContent(ms1), "files", "file1");
    content.Add(new StreamContent(ms2), "files", "file2");
    
  2. After you copy the contents of Request.Form.Files[0] into the MemoryStream, ms, you must also reset the position of the stream. Otherwise, the content sent to the server will be empty, as it will begin from the current position of the stream, which is at the end. Here's an example of resetting the position before adding the content:

    ms.Position = 0;
    content.Add(new StreamContent(ms));
    

Upvotes: 3

Related Questions