1

I'm trying to send multiple files with additional JSON data to the api. The api seems to support multiple content types.

How can i form the header with two content types 1. Multipart form data (for files) 2. application/json (for other json params)

Rajasekar
  • 18,392
  • 34
  • 106
  • 137
  • 1
    You can't. There would be no way of specifying which part if JSON and which part is multipart. There's no reason you can't send your JSON as a string value within the multipart request though – user184994 Nov 01 '18 at 08:09
  • multi-part is already _multiple parts_. So the files go in one part and the JSON in the other. – ADyson Nov 01 '18 at 09:55

1 Answers1

0

Thanks to Jack's answer on https://stackoverflow.com/a/24535293/9404093, I set up the following using different content types:

uploadFile(request: FileUploadRequest, file: File): Observable<FileUploadResponse> {
    const formData: FormData = new FormData();

    formData.append('details', new Blob(
      [JSON.stringify(request)],
      { type: "application/json" }
    ));
    formData.append('file', file, file.name);
    formData.append('contentType', file.type);

    return this.http.post<FileUploadResponse>(FILES_URI, formData);
  }

By using a Blob, you can assign a content type to the blob content (json).

Note this works with a Java Spring backend controller as well:

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<?> upload(@RequestPart FileUploadRequest details, @RequestPart MultipartFile file) {
    // TODO: the stuff
}
Charly
  • 881
  • 10
  • 19