尝试将文件上传到服务器

时间:2020-07-03 09:06:29

标签: angular typescript

我正在尝试将文件上传到服务器,但无法正常工作,并且出现此错误。

enter image description here

我不知道如何解决它。这是我的代码。

HTML

<div class="col-lg-4">
<input type="file" class="custom-file-input" #fileUploader (change)="uploadBanner($event.target.files)">
<label class="custom-file-label" #labelImport for="importFile"></label>
<ng-container *ngIf="uploadSuccess">Upload Successful</ng-container> 

组件

uploadBanner(files : File){
  let data={
   Id: this.confId,
   file: files[0].name,
   type: "Banner"
  }
  this.httpService.upload(data).subscribe(event =>{
   if (event.type === HttpEventType.DownloadProgress) {
     this.percentDone = Math.round(100 * event.loaded / event.total);
   } else if (event instanceof HttpResponse) {
     this.uploadSuccess = true;
   }
   
});
}

服务

public upload(file: File): Observable<HttpEvent<any>> {
    const formData: FormData = new FormData();
    formData.append('file', file);
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Bearer '+this.getToken()
      })
    };
    var header = {
      
      responseType: 'json',
      reportProgress: true,
    };
    return this.httpClient.post<any>(this.serverUrl + this.basePath + '/upload',{formData,header,httpOptions});
  }

1 个答案:

答案 0 :(得分:2)

问题在于您的upload()接受一个File对象,但是您正在发送一个创建的名为 data 的自定义对象,该对象在uploadBanner()中具有3个属性。

要使其生效,您可以直接将文件传递给upload()函数,或更改upload()参数的类型以匹配您的对象结构。

以下内容并不是一个完美的实现,但您应该对这个问题和预期的解决方案提供一个大概的认识吗?

uploadBanner(files : File){
  let data = {
    Id: this.confId,
    type: "Banner"
  }
  this.httpService.upload(files[0], data).subscribe(event =>{
    ...
  });
}
upload(file, data) {
  ...
  formData.append('file', file, file.name);
  formData.append('Id', data.Id);
  ...
}