【问题标题】:How to send Angular 6 object with image File to web-api?如何将带有图像文件的 Angular 6 对象发送到 web-api?
【发布时间】:2019-09-19 04:27:15
【问题描述】:

我想将带有其他表单详细信息的图像文件作为一个对象发布如下

export interface Employee {
    id: Guid;
    firstName: string;
    lastName: string;
    email: string;
    imgFile: File;
    enteredDate: Date;
}

这是我的服务

  addEmployee(employee: Employee) {
    return this.http.post(this.baseUrl + 'employees/add', employee);
  }

是否可以像上面那样发送文件?如果可能,如何在 asp.net core web api 中检索该文件?

  [HttpPost("add")]
  public void Add(EmployeeAddDto employeeAddDto)
  {
   ....// save employeeAddDto object to database
  }

EmployeeAddDtoimgFile的文件应该是什么?

【问题讨论】:

  • 您可以通过使用FormData 来检查此post-formdata
  • 如果您的 web-api 仅接受 json,那么您将无法将图像文件作为表单数据或图像作为 json 发送为此您几乎没有选项,例如具有 json 或 formdata 类型的用户 web-api,或者您可以首先将图像转换为base64,然后通过json发送,一旦你得到base64字符串服务器端解码回base64的图像然后我会工作

标签: angular typescript asp.net-core-webapi


【解决方案1】:

我认为您正在使用 dotnet 作为后端

    [HttpPost]
    [Route("api/values/Post")]       
    public HttpResponseMessage Post()
    {      

        foreach (var file in Request.Form.Files)
        {
            StreamReader sr = new StreamReader(file.OpenReadStream());
            \\
            \\your code
            \\
        }
    }

在角度使用 FormData 发送图像

【讨论】:

    【解决方案2】:

    上传文件需要在客户端使用formdata,在服务器端使用FromForm

    1. 客户端视图

      <input id="imgFile" type="file" (change)="addFile($event)" placeholder="Upload file">
      
    2. 客户端 JS

      public addFile(element) {
              let data = new FormData();
          data.append('firstName', 'f1');
          data.append('lastName', 'l1');
          data.append('imgFile', element.target.files[0]);
          this.http.post<any>(this.baseUrl + 'api/SampleData/add', data).subscribe(result => {
      
              });
      }
      
    3. 服务器 API

      [HttpPost("add")]
      public void Add([FromForm]EmployeeAddDto employeeAddDto)
      {
      }
      
    4. 型号

      public class EmployeeAddDto
      {
          public string Id { get; set; }
          public string FirstName { get; set; }
          public string LastName { get; set; }
          public string Email { get; set; }
          public IFormFile ImgFile { get; set; }
          public DateTime EnteredDate { get; set; }
      }
      

    【讨论】:

      【解决方案3】:

      基本上,您可以使用 Form Data 向您发送数据对象/模型和文件。这样做的简单技巧就是 stringify 你的对象。 这是一个例子

      让 formDatavar = new FormData(); formDatavar.append("文件",文件详细信息,文件名) formDatavar.append("ModelData",JSON.stringify(ModelDataFromUI))

      然后你可以使用 formDatavar 来发送你的数据

      最后你需要在后端服务中将你的字符串转换为对象

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-15
        • 2020-11-01
        • 2014-12-19
        • 1970-01-01
        • 2019-03-27
        • 1970-01-01
        • 2012-12-01
        • 1970-01-01
        相关资源
        最近更新 更多