0

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?

saiftg
  • 43
  • 7

3 Answers3

2

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);
tufonas
  • 303
  • 1
  • 7
0
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);
  });
Segun Adeniji
  • 370
  • 5
  • 11
  • you can add it like that, do not forget to import { HttpClient, HttpHeaders } from '@angular/common/http'; and add it in your constructor – Segun Adeniji Feb 03 '22 at 00:23
-1

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.

KSoze
  • 141
  • 3
  • Setting a Content-Type different from the type of the requests content is NOT good. An API that accepts that kind of request is not well designed. – KSoze Feb 03 '22 at 08:13