Search code examples
angularjsfile-uploadhttp-postangular2-formshttp-status-code-400

File Upload Angular2 via multipart/form-data, 400 Error


I need to upload a file together with some meta info via multipart/form-data like this:

Header
----boundary
Meta
----boundary
File
----boundary

For some reason I always get a 400 Error, the Backend server tells me, that the Meta-Field is missing. However, if I look into the Hex/Ascii dump with Wireshark, the field is definitely there.
The following Curl-command works perfectly fine and the file gets uploaded successfully:

curl -H "Expect:" -v -i -X POST -H "Content-Type: multipart/form-data" -H "Authorization: "token" -F "File=@/location" -F 'Meta={"access":"token"}' http://path

Therefore this doesn't seem to be a Backend failure. My Angular (4.1.3) request must be bad, but I can't figure out what's wrong with it.

Template-Code:

<input #file_input type="file" (change)="onFileInputChange($event)" multiple>

Angular2-Code:

onFileInputChange(event) {
  let fileList: FileList = event.target.files;
  for (let i = 0; i < fileList.length; i++) {
    let fp: File = fileList[i];
    let formData: FormData = new FormData();
    formData.append('File', fp, fp.name);
    const body = JSON.stringify({
       'access': "token"
    });
    this.formData.append('Meta', body);
    let RequestHeader = new Headers();
    // auto set content type
    RequestHeader.append('Content-Type', '');
    RequestHeader.append('Accept', 'application/json');
    RequestHeader.append('Authorization', "token");

    this.http.post(this.backend_url, formData, RequestHeader).map(
    res => res.json()).subscribe(
            data => console.log('success'),
            error => console.log(error))
  }
}

What am I missing here?


Solution

  • I finally found the solution. The Content-Type header was malformed:

    Content-Type: , multipart/form-data; boundary=----WebKit12345
    

    The content type header in the actual code was preset. By calling

    headers.set('Content-Type', '');
    

    I assumed, that the header content type was overwritten, but actually an empty string was prepended to it, so that there was a comma, which could not be parsed, of course.
    I solved this by deleting the content type header completely:

    headers.delete('Content-Type');