Java 使用AJAX将文件上载到Spring Boot应用程序时出现问题
我正在努力使用AJAX将文件上传到我的Spring Boot应用程序。我读了很多教程,看了很多视频,但不知怎么的,它仍然不适合我。我有一个classJava 使用AJAX将文件上载到Spring Boot应用程序时出现问题,java,ajax,spring-boot,Java,Ajax,Spring Boot,我正在努力使用AJAX将文件上传到我的Spring Boot应用程序。我读了很多教程,看了很多视频,但不知怎么的,它仍然不适合我。我有一个class帐户,我想把头像上传到这里。这是我的代码: JS: 爪哇: 当我上传文件时,我得到一个Java警告: 2020-09-08 02:36:58.232警告14140---[nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver:已解决 [org.springframework.web.mult
帐户
,我想把头像上传到这里。这是我的代码:JS: 爪哇: 当我上传文件时,我得到一个Java警告:
2020-09-08 02:36:58.232警告14140---[nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver:已解决 [org.springframework.web.multipart.support.MissingServletRequestPartException: 所需的请求部分“imageFile”不存在] 在我的浏览器的控制台中:
jquery-3.5.1.min.js:2个帖子 http://localhost:8080/user/my-帐户/上传化身图像400 现在我不知道哪一边有错误的代码。
谁能解释一下我的代码有什么问题吗?好吧,我有点笨,这很简单
@RequestParam
必须与我输入的formData.append(“file”,file)
匹配。因此,在本例中,我需要向@RequestParam
添加我附加到formData
的值:
@RequestParam(“文件”)
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);
});
});
@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;
}