代码之家  ›  专栏  ›  技术社区  ›  yer

角度4-如何将文件以POST形式发送到后端

  •  3
  • yer  · 技术社区  · 6 年前

    我在表格里有一个文件上传。我需要创建这个上传的文件和一些其他表单域到后端的post请求。

    以下是我的代码:

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

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

    2 回复  |  直到 6 年前
        1
  •  6
  •   dark_gf    6 年前

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

    '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?

        2
  •  0
  •   borbesaur    6 年前

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

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

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

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