Search code examples
angularasp.net-coreiformfile

FromForm with IFormFile using Asp.net Core


I want to upload an Image file with Model data so I am using FromForm with IFormFile in Asp.net core api.

[HttpPost]
public IActionResult AddData([FromForm] AddDataModel addDataModel, IFormFile formFile)
{
     // Logic here...
}

I am using Angular 7 in the frontend side. I am adding model data and file to FormData and trying to send it but It always all model fields values null.

What is the right way to solve this?


Solution

  • The formfile has to be inside your AddDataModel csharp class.

    Like this

    public class AddDataModel 
    {
       public IFormFile File { get; set; }
       // more properties
    }
    

    Then in your angular-service, do the following

    public add(model: AddDataModel): Observable<any> { // file can be passed as parameter or inside typescript model
       const formData = new FormData();
       // optional you can pass a file name as third parameter
       formData.append('file', model.file)
       // add more keys to the form-data
       return this.http.post<any>('my-http-url', formData);
    }
    

    Now update the endpoint

    [HttpPost]
    public IActionResult AddData([FromForm] AddDataModel addDataModel)
    {
         // Logic here...
    }
    

    Now the modelbinder of ASP.NET Core will map the form file retrieved from the form-data.

    Edit:

    Added a simple sample on github ready to be cloned.