4

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 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Thanks - tried that but didn't make a difference, there's not that much actually fundamentally different from our code tbh
removing the Content-Type fixed it for me. Doing so will automatically add the correct Content-Type+ boundary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.