Search code examples
angularspring-bootmultipartform-data

Cannot POST request multipart/form-data angular


I am trying to post formData through angular code. I am using httpInterceptor for adding request headers.

Here goes my code:

httpInterceptor ---

if (request.url.includes(baseUrl)) {
        request = request.clone({
          headers: new HttpHeaders({
            'Request-Date': currentDate.toString(),
            'Request-Id': requestId,                
            "Accept": "application/json" ,
            param1: environment.encriptionEnabled
              ? requestData['param1']
              : 'null',
            locale: 'en',
          }),
          body: environment.encriptionEnabled
            ? requestData.ciphertext
            : request.body
        });
      }

Using postman I am able to post correctly. But through code it gives error.

enter image description here

enter image description here

Looks like I am doing something wrong. Any help will be highly appreciated.

Thanks

enter image description here

controller method ---

@PostMapping(value = RequestURIConstant.SEND_EMAIL_WITH_ATTACHMENT, consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE })
public void sendEmailWithAttachment(@RequestPart("request") String request, @RequestPart("file") MultipartFile file) {
  EmailNotificationRequest emailRequest = externalNotification.getJson(request);
  LOG.info("Request received to send email");
  externalNotification.sendMail(emailRequest, file);
}

Error logged on server ---

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

If I remove Content-Type as suggested on some posts then I get unsupported media type error


Solution

  • After spending nights I was able to fix this. The main issue was my content-type and the way I was creating formData object.

    Here is my changes which worked:

    1. Firstly I removed the content-type mentioned in my httpInterceptor

    2. Since i needed to mention content-type for each part of the multipart request. I constructed using blob as blob gives us priviledge to specify content-type


    let formData = new FormData();
    formData.append('request', new Blob([JSON.stringify(obj)],{type: "application/json"}));