使用AJAX将文件上传到Spring Boot应用程序时出现问题。

huangapple go评论62阅读模式
英文:

Problem with uploading files to Spring Boot app using AJAX

问题

我在使用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  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]

而且在我的浏览器控制台中显示:

> jquery-3.5.1.min.js:2 POST
> http://localhost:8080/user/my-account/upload-avatar-image 400

目前我不知道哪一方的代码有问题。是否有人可以解释一下我的代码有什么问题吗?
英文:

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:<br>
JS:

inputAvatar.on(&#39;change&#39;, function(e) {
    e.preventDefault();
    var file = inputAvatar.prop(&#39;files&#39;)[0]
    var formData = new FormData();
    formData.append(&quot;file&quot;, file)

    $.ajax({
        url: &quot;/user/my-account/upload-avatar-image&quot;,
        type: &quot;post&quot;,
        data: formData,
        enctype: &#39;multipart/form-data&#39;,
        cache: false,
        processData: false,
        contentType: false
    }).done(status =&gt; {
        console.log(status);
    });
});

Java:

    @PostMapping(value = &quot;/my-account/upload-avatar-image&quot;)
    public int uploadAvatarImage(@RequestParam MultipartFile imageFile){
        return accountService.uploadAvatarImage(imageFile);
    }
    public int uploadAvatarImage(MultipartFile imageFile){
        String folder = this.getClass().getResource(&quot;/images/avatars&quot;).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:<br>

> 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:<br>

> 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.<br>
Can anyone explain to me what is wrong with my code?

答案1

得分: 0

好的,我有点儿笨,这相当简单。@RequestParam 必须与我放入 formData.append("file", file) 的内容匹配。所以在这种情况下,我需要将我附加到 formData 的值添加到 @RequestParam 中:
@RequestParam("file")

英文:

Ok, I'm kinda dumb, it was pretty easy. @RequestParam has to match what I put into formData.append(&quot;file&quot;, file). So in this case I need to add a value of what i append to formData to @RequestParam:
@RequestParam(&quot;file&quot;)

huangapple
  • 本文由 发表于 2020年9月8日 08:48:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63785781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定