无法将数据追加到FormData

时间:2018-06-22 07:13:59

标签: angularjs typescript multipartform-data

我正在尝试将文件作为多部分/ form-data 上载到服务器。为此,我创建了 FormData 的对象,并将文件及其名称附加到该对象。不幸的是,该追加未发生,并且没有显示为错误。请帮助我解决此问题。以下是我尝试过的代码。

HTML

  <input style="font-size:15px;" name="file" type="file" (change)="fileChangeEvent($event)" placeholder="Upload a file..."/>

      <button [disabled]="!this.fileCollection.length>0" type="button" class="btn btn-primary btn-s" (click)="uploadFile()" style="position:relative; top: 12px;"> 
          Upload
      </button>

component.ts

fileChangeEvent(fileInput: any): void {
    this.filesToUpload = fileInput.target.files;
    this.uppendFileCollections(this.filesToUpload);
  }

  uppendFileCollections(files): void {
    for (var index = 0; index < files.length; index++) {
      {
        this.fileCollection.push(<TemplateForm>
          {
            fileData: files[index],
            fileName: files[index].name
          }
        );
      }
    }

    this.fileUploaderTitle = this.fileCollection.length + ' file(s) selected.';
  }

  uploadFile() {
    let file: File = this.fileCollection[0]['fileData'];//passing only one file now.

    this.homeService.saveFile(file)
      .then((response) => {
        if (response.message == 'success') {
          this.filesToUpload = [];
          this.fileCollection = [];
          this.fileUploaderTitle = 'Choose Files';
          this.showSnackBar();
          this.isLoading = false;
        }
        else {
          console.log('Error on upload:' + response.error);
        }
        this.router.navigate(['/result'])
      })
  }

Service.ts

saveFile(file: File): Promise<any> {
        let uri = `${this.serverApi}/fileUpload`;
        let playload: FormData = new FormData();
        playload.append('file', file,file.name);
        let headers = new Headers();
        headers.append('Content-Type', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        return this.http.post(uri, playload, options)
          .toPromise()
          .then((res) => {
            let temp = res.json();
            return { 'statusCode': 200, 'message': 'success', 'result': temp, 'error': {} };
          }
          )
          .catch((error) => {
            return { 'statusCode': 200, 'message': 'failed', 'result': {}, 'error': error };
          }
          )
      }

1 个答案:

答案 0 :(得分:0)

使用这种简单格式:

saveFile(data)
{
 let uri = `${this.serverApi}/fileUpload`;
 const formData: FormData = new FormData();
 formData.append('file',file,file.name);
 return this.http
  .post(uri, formData)
  .map(() => { return true; })
}