Home > Back-end >  Current request is not of type MultipartHttpServletRequest
Current request is not of type MultipartHttpServletRequest

Time:08-16

I'm trying to send an image object from Angular to Spring Boot but everytime I try I get this error:

Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]

This is my Angular code:

addPostWithIMG(image: File, postRequest: PostRequest): Subscription {
const headers = new HttpHeaders();
headers.append('Content-Type', ' multipart/form-data content');
var file: FormData = new FormData();
file.append('file', image);
file.append('postRequest', JSON.stringify(postRequest));
console.log(file)
return this.http.post<PostRequest>(`${this.baseUrl   "multi"}`, file, {headers: headers}).subscribe({
  next: (data: any) => {
    console.log(data)
  },
  error: (err: any) => {
    console.error(err)
  },
  complete: () => {
    console.log("Done")
  }
});

}

This my Spring Boot side:

  @PostMapping(path = "multi")
public String multi(MultipartHttpServletRequest request) throws IOException {
    String postJSON = request.getParameter("postRequest");
    PostRequest = new Gson().fromJson(post, PostRequest.class);
    MultipartFile file = request.getFile("file");
    Binary files = new Binary(file.getBytes());
    File fileToSave = new File("Post/src/main/resources/"   postRequest.getPostId()   ".png");
    log.info("file: {}", fileToSave.getAbsolutePath());
    if (!fileToSave.exists()) {
        log.info("file created: {}", fileToSave);
        fileToSave.createNewFile();
    } else {
        log.info("file already exist: {}", fileToSave);
    }
    // Try-with-resource
    try (OutputStream out = new FileOutputStream(fileToSave.getAbsolutePath())) {
        out.write(files.getData());
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "Image saved";
}

Can Anyone help me to find the reason of thi exception Thank you very much

CodePudding user response:

Try to don't add:

headers.append('Content-Type', ' multipart/form-data content');

The web will automatically set for you

  • Related