0

I'm trying to upload file to server but not working and I got this error..

enter image description here

I don't have any idea how to fix it.. This is my code..

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> 

Component

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

Service

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});
  }
javiens
  • 61
  • 1
  • 8
  • 21

1 Answers1

2

The problem is that your upload() accepts a File object, but you are sending a custom object that you created named data with 3 attributes in uploadBanner().

To make it work, you can directly pass files to the upload() function, or change the type of the upload() parameter to match your object structure.

The following wouldn't be a perfect implementation, but should you give you a rough idea about the issue and expected solution.

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);
  ...
}
Nayak
  • 742
  • 6
  • 7