'How to make a POST req in angular/typescript with file and JSON

I'm trying to send a file and json object via post method. Code sample :

serviceFunction(file, jsonObjAlreadyStringified){

const url : 'something'
const params: 'some params'

const reqBody: FormData = new FormData();
reqBody.append('file',file)
reqBody.append('json', jsonObjAlreadyStringified)

return this.http.post(url, reqBody, {params, responseType: 'arrayBuffer'});

}

I managed to hit the server, but was getting 415 unsupported media. Tried and postman and it worked after I specified the 'json' content-type as "application/json"

So my question is, how do I define the content-type for the json and send it along with the file?



Solution 1:[1]

You can use Blob to pass data and the type of the data.

const reqBody: FormData = new FormData();
reqBody.append('file',file)
reqBody.append('json', new Blob([jsonObjAlreadyStringified],{ type: 'application/json' }));

return this.http.post(url, formData);

Solution 2:[2]

var headers = new HttpHeaders();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json');
const requestOptions = { headers: headers };

const reqBody: FormData = new FormData();
reqBody.append('file',file);
reqBody.append('json', jsonObjAlreadyStringified);

let url = `something`;
this.http.post(url, reqBody, requestOptions)
  .subscribe(response => {
    console.log(response);
  }, error => {
    console.log(error);
  });

Solution 3:[3]

In a HTTP request you can set only one Content-Type header which would be 'multipart/form-data' when uploading the file and 'application/json' for JSON metadata.

Sending (uploading) a file must be done in a separate request, linked metadata (if needed) can be sent in a second request.

In most applications, sending the file returns an identifier referencing that file, and the second request dhould use that identifier to link the metadata to the file.

You can find good examples of uploading file for multiple Angular versions here File Upload In Angular?

Sending the metadata will be a simple HTTP POST with the right Content-Type, 'application/json' in your case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tufonas
Solution 2 Segun Adeniji
Solution 3 KSoze