FromForm with IFormFile using Asp.net Core

♀尐吖头ヾ 提交于 2019-12-14 04:11:28

问题


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:


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.



来源:https://stackoverflow.com/questions/54424712/fromform-with-iformfile-using-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!