4

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?

1 Answer 1

11

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.

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

6 Comments

Do I need to remove IFromFile from API method level?
Yes, it will only be inside your csharp class.
It worked. As FormData doesn't accept Model, I need to use JSON.stringify so API is not validating Model through a filter. How do I solve it?
If you're using FormData then you actually have to build your form data with that. You can't just create a JSON string of a complex object and pass the string. You may be better served here by actually submitting JSON, instead. For your file upload, you simply need to read the file bytes and create a Base 64 encoded string to pass in your JSON. Server-side, you'll bind that to a byte[] instead of IFormFile then.
@ChrisPratt I was using Base 64 encoded string before but sometimes, if file size is large then it hangs up the browser.
|

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.