【发布时间】:2020-09-08 00:48:30
【问题描述】:
我正在努力使用 AJAX 将文件上传到我的 Spring Boot 应用程序。我阅读了许多教程,观看了许多视频,但不知何故,它仍然对我不起作用。我有一个班级Account,我想上传头像到这个。这是我的代码:
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;
}
当我上传文件时,我收到 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 POST http://localhost:8080/user/my-account/upload-avatar-image 400
现在我不知道哪一边有错误的代码。
谁能向我解释我的代码有什么问题?
【问题讨论】:
标签: java ajax spring-boot