2

In my Angular application I am using a control: https://github.com/valor-software/ng2-file-upload

This control does a post with a file to my .NET core web API. Here is a short example, which is not really important.

public uploader: FileUploader = new FileUploader({url: `${environment.apiBaseUrl}/file`});

Eventually the control does a post to this .NET core web api action:

[Route("[controller]")]
public class FileController : Controller
{
    [HttpPost]
    public void Post(IFormFile uploadedFile)
    {
        var file = uploadedFile;
        _fileSystemProvider.SaveToFileSystemAsync(_uploadSettings.GetReplacedDirectoryPath(), file.FileName, file.OpenReadStream());
    }
}

enter image description here The file upload is posting to the .NET web api, confirmed using the console in Chrome, but the uploadedFile parameter is NULL.

Why is this happening?

Nick N.
  • 12,902
  • 7
  • 57
  • 75

1 Answers1

3

It turns out that the name of the parameter in your post action is really important.

I figured out that ng2-file-upload was using file as the name attribute in the fileInput.

So when I changed my post action parameter from uploadedFile to file everything worked fine!

    [HttpPost]
    public void Post(IFormFile file)
    {
        _fileSystemProvider.SaveToFileSystemAsync(_uploadSettings.GetReplacedDirectoryPath(), file.FileName, file.OpenReadStream());
    }

My problem was with ng2-fileupload, but you can also have this with any other plugin in any other framework! Make sure the name attribute of your file input or upload control is equal to the name of the IFormFile parameter of the Post action in your .NET web api!

Nick N.
  • 12,902
  • 7
  • 57
  • 75
  • Yes. That's result of the modelbinder. The file data you're posting is just a stream of bytes. ASP.NET Core needs to know how to bind that to something useful, which is where your `IFormFile` param comes into play. However, the modelbinder gets the data with a "file" key and there's nothing named "file" to bind it to, so it does what it does for all such binding errors and simply discards the posted data. Changing the param name gave it something to actually bind to, so yes, parameter names are crucially important. – Chris Pratt May 03 '18 at 17:53
  • @chris Thanks for the clarification, if you want you could edit my answer accordingly – Nick N. May 03 '18 at 19:00
  • 1
    If you need a greater control on both the API and on the client regarding ng2-file-upload, you can check my answer here https://stackoverflow.com/questions/48751058/multiple-form-data-file-upload-parameters/48752960#48752960 – Felix Too May 04 '18 at 08:59