Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 979
Jeeten Parmar Avatar asked Sep 18 '25 04:09

Jeeten Parmar


1 Answers

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.

like image 163
alsami Avatar answered Sep 19 '25 19:09

alsami