2

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

Amit
  • 1,460
  • 1
  • 14
  • 39
  • Did you check answer in https://stackoverflow.com/questions/56184305/the-request-was-rejected-because-no-multipart-boundary-was-found-angularspring or https://stackoverflow.com/questions/31089824/the-request-was-rejected-because-no-multipart-boundary-was-found-with-angularjs – Ori Marko Jun 19 '22 at 07:27
  • @user7294900 Yes I have tried. It didnt work for me – Amit Jun 19 '22 at 07:40
  • One more finding I have that when I copy my curl and use it in Post-man, to make it work I have to add content-type for each key explicitly . This is same for the curl shared by backend team – Amit Jun 19 '22 at 07:41

1 Answers1

2

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"}));
Amit
  • 1,460
  • 1
  • 14
  • 39