0

Google 'Angular 8 Springboot File Upload'. I tried the first 3 pages. Couldn't upload a damn file.

Furthest I got was:

Resolved [org.springframework.web.multipart.MultipartException: Current request is not a multipart request]

Tried everything I could.

I just want to send a file from Angular and receive it in a spring boot rest controller. Could someone please help me out with that?

Back End:

@PostMapping("/users/profile/upload")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> uploadData(@RequestParam("file") MultipartFile file)
        throws Exception {
    if (file == null) {
        throw new RuntimeException("You must select the a file for uploading");
    }
    String originalName = file.getName();

    // Do processing with uploaded file data in Service layer
    return new ResponseEntity<String>(originalName, HttpStatus.OK);
}

Front end service:

uploadFile(file: File): Observable<any> {

const formData = new FormData();

formData.append('file', file, 'file');
const headers = new HttpHeaders({
  'Content-Type': 'multipart/form-data'
});
const options = { headers };

return this.http.post(`${this.baseUrl}/profile/upload`, formData, options);
}
4
  • can you show you API code and how you are consuming api? Commented Feb 25, 2020 at 12:01
  • @Mustahsan sure! Just added them Commented Feb 25, 2020 at 12:17
  • did you tried making http call without headers? Commented Feb 25, 2020 at 12:28
  • @Mustahsan yes I did. Same result : [org.springframework.web.multipart.MultipartException: Current request is not a multipart request] Commented Feb 25, 2020 at 12:33

1 Answer 1

1

Your code looks good to me. You don't need to add the headers in Angular, and you don't need to send options, but I don't think it makes a difference.

I wonder if Angular actually sends a file. You can check with console.log(file), which you can add in your front-end service.

You may also check what comes into Spring Boot. How about changing the signature to

public ResponseEntity<String> uploadData(HttpServletRequest request) throws Exception

This allows you to X-ray to request, and see what's coming through. I hope these pointers are useful.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Indeed I had to add the Authorization header and it works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.