[英]Sending a file from angular to web api as a property
在 angular model
MyClass.ts
name: string
age: number
file: File
在 web api 保存(MyClassDto)
MyClassDto.cs
string name;
int age;
IFormFile file;
从 UI 中单击按钮:
MyClass 通过
name='test'
age=10,
file=document.getElementById('fileElement').files[0]; -> for ex:'C:\fakepath\testfile.jpg"
当调用 web api 时,我收到此错误:
api - 将 d 传递给 object 作为参数的 post 方法。
保存(MyClassDto myClassDto);
不支持接口类型的 IFormFile 反序列化错误。
知道当 IFormFile 是两个模型中的属性时如何发送文件吗?
您需要在 web API 中创建一个实现 IFormFile 接口的 class。 接口并不意味着被实例化,因此它不能在 webapi 代码中反序列化。
然后您应该将 web api myclassDto 的参数签名更改为:
string name;
int age;
NewFormFileClassThatImplementsTheIFormFile file;
看来,我需要使用 FormData,没有 object 轻松映射。
const formData=new FormData();
formData.append('name', 'test name');
formData.append('file', file);
save(formData);
然后,api 接收 model 和文件。
另外,不要忘记在 api 方法后添加 [FromForm]
Save([FromForm] MyClassDto myClassDto);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.