I'm struggling with uploading files to my Spring Boot app using AJAX. I read many tutorials, watched many videos and somehow, it still doesn't work for me. I have a class Account and i want to upload avatar to this. Here is my code:
JS:
inputAvatar.on('change', function(e) {
e.preventDefault();
var file = inputAvatar.prop('files')[0]
var formData = new FormData();
formData.append("file", file)
$.ajax({
url: "/user/my-account/upload-avatar-image",
type: "post",
data: formData,
enctype: 'multipart/form-data',
cache: false,
processData: false,
contentType: false
}).done(status => {
console.log(status);
});
});
Java:
@PostMapping(value = "/my-account/upload-avatar-image")
public int uploadAvatarImage(@RequestParam MultipartFile imageFile){
return accountService.uploadAvatarImage(imageFile);
}
public int uploadAvatarImage(MultipartFile imageFile){
String folder = this.getClass().getResource("/images/avatars").getPath();
try {
byte[] bytes = imageFile.getBytes();
Path path = Paths.get(folder + imageFile.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(imageFile);
return 0;
}
When i upload file i get a Java warning:
2020-09-08 02:36:58.232 WARN 14140 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'imageFile' is not present]
and in the console of my browser:
jquery-3.5.1.min.js:2 POST http://localhost:8080/user/my-account/upload-avatar-image 400
and for now i don't know on which side there is a wrong piece of code.
Can anyone explain to me what is wrong with my code?