0

I use Angular 9 to send POST requests to a REST API running on Tomcat 9 and Jersey 2.32.

All my requests run fine except the one I am currently developing and which is a POST request to upload a file and then run a task on this file.

Although the file is uploaded and the progress indicator is correct, I get a HTTP 400 error on this request with invalid request syntax.

I cannot figure out what is wrong in my code, so any advice appreciated.

Here is my Angular code sending the POST request:

   const authorizationString = GlobalVariablesService.customerName + ':' + this.token.getToken();
   const requestOptions = {
     reportProgress: true,
     headers: new HttpHeaders({
       'Content-Type': 'multipart/form-data',
       Authorization: authorizationString
     }),
   };
   const formData = new FormData();
   formData.append('file', GlobalVariablesService.selectedFile);
   const req = new HttpRequest(
     'POST',
     GlobalVariablesService.adminConfig.metaLmsApiUrl + 'userImport',
     formData,
     requestOptions
   );
   return this.httpClient.request(req).pipe(
     map(event => this.getEventMessage(event, GlobalVariablesService.selectedFile)),
     tap(message => this.showProgress(message)),
     last(), // return last (completed) message to caller
     catchError(this.handleError(GlobalVariablesService.selectedFile)),
   );

Here is the Java code which receives the request:

@Path("/userImport")
public class UserImportRest {

   ErrorResponseRec errorResponse;

   @POST
   @Consumes(MediaType.MULTIPART_FORM_DATA)
   @Produces({ MediaType.APPLICATION_JSON })   
   public ErrorResponseRec uploadFile(
           @FormDataParam("file") InputStream uploadedInputStream,
           @FormDataParam("file") FormDataContentDisposition fileDetail) {
       // save file
       System.out.println("upload here");
       String uploadedFileLocation = "C://LMS//resources//local//uploaded/" + fileDetail.getFileName();
       writeToFile(uploadedInputStream, uploadedFileLocation);
       String output = "File uploaded to : " + uploadedFileLocation;
       errorResponse = new ErrorResponseRec(output);
       return errorResponse;
   }

   // save uploaded file to new location
   private void writeToFile(
           InputStream uploadedInputStream,
           String uploadedFileLocation) {

       try {
           OutputStream out
                   = new FileOutputStream(
                           new File(
                                   uploadedFileLocation));
           int read = 0;
           byte[] bytes = new byte[1024];

           out = new FileOutputStream(new File(uploadedFileLocation));
           while ((read = uploadedInputStream.read(bytes)) != -1) {
               out.write(bytes, 0, read);
           }
           out.flush();
           out.close();
       } catch (IOException e) {
           e.printStackTrace();
       }

   }

}
Eric Malalel
  • 185
  • 1
  • 17

1 Answers1

0

Thanks to FormData how to get or set boundary in multipart/form-data - Angular, here is the fix:

Do not set Content-Type header.

    const requestOptions = {
      reportProgress: true,
      headers: new HttpHeaders({
        Authorization: authorizationString
      }),
    };
Eric Malalel
  • 185
  • 1
  • 17