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?

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

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 Thanks for the clarification, if you want you could edit my answer accordingly
If you need a greater control on both the API and on the client regarding ng2-file-upload, you can check my answer here stackoverflow.com/questions/48751058/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.