FromForm with IFormFile using Asp.net Core

后端 未结 1 1641
南旧
南旧 2021-01-14 20:47

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

[HttpPost]
p         


        
相关标签:
1条回答
  • 2021-01-14 21:42

    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.

    0 讨论(0)
提交回复
热议问题