Reputation: 41
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);
}
Upvotes: 0
Views: 395
Reputation: 597
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.
Upvotes: 1