【问题标题】:angular 4- How do I send file in POST to backend角度 4-如何在 POST 中将文件发送到后端
【发布时间】:2019-01-01 14:55:50
【问题描述】:

我在表单中有一个文件上传。我还需要使用这个上传的文件和其他一些表单字段创建发布请求到后端。

下面是我的代码:

      fileChange(event) {

        const fileList: FileList = event.target.files;
        if (fileList.length > 0) {
          this.file = fileList[0];
          this.form.get('file_upload').setValue(this.file);
        }
      }


      onClick(){

        const val = this.form.value;

             const testData = {
              'file_upload': this.file,
              'id': val.id,
              'name' : val.name,
              'code': val.code,
          };

        this.http.post('https://url', testData,
          .subscribe(
            response => {
              console.log(response);
            });
        }

除了上传的文件外,每个字段值都被发送到后端。我如何将上传的文件与表单字段一起发送到后端? 如果需要任何其他信息,请告诉我。

【问题讨论】:

    标签: angular file-upload angular4-forms


    【解决方案1】:

    假设您正在服务器上正确处理文件上传(通常是某种类型的 npm 包,如 multer 或 busboy),

    您需要在 angular 端使用 npm 包来处理多部分表单数据。

    ng-2-file-upload 是其中之一。

    https://www.npmjs.com/package/ng2-file-upload

    【讨论】:

      【解决方案2】:

      你只是在尝试简单的传递文件数据

      'file_upload': this.file,
      

      这是错误的

      上传文件的方法有很多种,我喜欢用FormData,你的例子:

      let testData:FormData = new FormData();
      testData.append('file_upload', this.file, this.file.name);
      this.http.post('https://url', testData).subscribe(response => {
          console.log(response);
      });
      

      更多详情在这里File Upload In Angular?

      【讨论】:

      • 我也尝试过使用 formData。但是当我发出发布请求时,formData 变成了空的。
      • @yer 你试过添加标题吗? headers.append('Content-Type', 'multipart/form-data');
      猜你喜欢
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 2016-07-23
      相关资源
      最近更新 更多