【问题标题】:Sending a file from angular to web api as a property将文件从 angular 发送到 web api 作为属性
【发布时间】:2021-06-10 23:10:16
【问题描述】:

在角度模型中

MyClass.ts
  name: string
  age: number
  file: File

在网页 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 - 将 dto 对象作为参数传递的 post 方法。

保存(MyClassDto myClassDto);

不支持接口类型的IFormFile反序列化错误。

知道当 IFormFile 是两个模型中的属性时如何发送文件吗?

【问题讨论】:

    标签: c# angular asp.net-web-api angular8 webapi


    【解决方案1】:

    您需要在 Web API 中创建一个实现 IFormFile 接口的类。接口不是用来实例化的,所以不能在 webapi 代码中反序列化。

    那你应该把web api myclassDto的参数签名改成:

    string name;
     int age;
     NewFormFileClassThatImplementsTheIFormFile file;
    

    【讨论】:

      【解决方案2】:

      看来,我需要使用FormData,没有容易的对象映射。

      const formData=new FormData();
      formData.append('name', 'test name');
      formData.append('file', file);
      save(formData);
      

      然后,api 接收模型和文件。

      另外,不要忘记在 post api 方法中添加 [FromForm]

      保存([FromForm] MyClassDto myClassDto);

      【讨论】:

        猜你喜欢
        • 2017-01-17
        • 2018-03-07
        • 1970-01-01
        • 1970-01-01
        • 2020-03-15
        • 1970-01-01
        • 2020-04-18
        • 2012-05-11
        • 2019-10-24
        相关资源
        最近更新 更多