Problem uploading file with FormData in Angular 6

Viewed 6720

I'm trying to build a file upload system with Angular 6 for the UI and Lumen for the API. The file upload works fine when I use the API directly with Postman. But it's not working with the Angular UI. I'm using FormData to handle the uploading but the API returns a null value for the file I'm trying to upload.

HTML:

<input type="file" name="document" (change)="onFileChanged($event.target.files)">

Angular code:

public onFileChanged(files: any): void {
    var file = files[0];
    var fd = new FormData();
    fd.append('document', file);
    this.documentService
        .uploadDocument(this.id, fd)
        .subscribe(
            () => {
                console.log('success');
            },
            () => {
                console.log('failure');
            }
        );
}
2 Answers

OK I found the problem!

It was because I was using an interceptor that was adding JSON headers to every request so it was converting everything to JSON which obviously wouldn't work. So I just removed that header and it worked.

I have used form data in my project. have a look in my code.it may help you

       uploadFile(data, index) {
          const formData: FormData = new FormData();
          console.log('formData', formData);

          formData.append('data', this.tableData.caseId);
          formData.append('file', data.filedata);
          this.dashService.uploadAttachment(formData, this.encodedData)
            .subscribe(
              (respData) => {
                this.filesArray.splice(index, 1);
              },
              respError => {
                console.log('respError', respError);
              }
            );
        }
        removeFile(index) {
          this.filesArray.splice(index, 1);
        }

The below is the service used in the code.

     uploadAttachment(data, encodedData) {
        return this._http.post(this._url + 'cases/attachment', data, {
          headers: {
            // 'Content-Type': 'multipart/form-data',
            'Accept': 'application/json',
            'Authorization': encodedData
          }
        });
      }

I was facing problem for the content type i was using in the service. So i have commented it and my code worked fine.

Related