1

I want to upload so files from my Angular 5 frontend. I am using the Django Rest Framework in my backend.

This is my Angular service to upload the file:

  uploadStudentFile(solution_id: number, file: File): Observable<SolutionRealFile> {
    let url = `${this.url}/solutions/${solution_id}/file_uploads/`;
    const formData: FormData = new FormData();
    formData.append('file_src', file, file.name);
    return this.httpClient.post<SolutionRealFile>(url, formData, { headers: this.headers })
      .pipe(
        catchError(this.handleError('Upload file', new SolutionRealFile()))
      );
  }

When running the request from my app in the browser, the request fails with HTTP/1.1" 400 73 and this is the error message:

{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}

But running the same request with the same file form Postman, everything is working. I am new to Angular 5, maybe is just a small problem not sure.


Edit 1:

The headers:

'Content-Type': 'application/json',
'Authorization': `JWT ${localStorage.getItem(TOKEN_NAME)}`
Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
Max
  • 1,368
  • 4
  • 18
  • 43

1 Answers1

0

To use HttpClient with FormData, you will need to add 'enctype': 'multipart/form-data' to your headers and remove the content-type header.

content-type will be then automatically set by browser based on generated form boundary, and also you need the multipart encoding type just like you would need that in case of plain html form. That way your server will be able to read the file same way as it would be sent thought plain html form.

More about why you need that multipart type can be found in this post: What does enctype='multipart/form-data' mean?

Martin Adámek
  • 16,771
  • 5
  • 45
  • 64