使用Asp.net Core与IFormFile一起使用FromForm [英] FromForm with IFormFile using Asp.net Core

查看:1535
本文介绍了使用Asp.net Core与IFormFile一起使用FromForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传包含模型数据的图像文件,因此我在Asp.net core api中将FromFormIFormFile一起使用.

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...
}

我在前端使用Angular 7.我正在将模型数据和文件添加到FormData,并尝试发送它,但所有模型字段值始终为null.

解决这个问题的正确方法是什么?

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?

推荐答案

表单文件必须位于AddDataModel csharp类中.

The formfile has to be inside your AddDataModel csharp class.

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);
}

现在更新端点

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

现在,ASP.NET Core的modelbinder将映射从表单数据中检索到的表单文件.

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

github 上添加了一个简单示例,准备对其进行克隆

Added a simple sample on github ready to be cloned.

这篇关于使用Asp.net Core与IFormFile一起使用FromForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆