【问题标题】:Problem with uploading files to Spring Boot app using AJAX使用 AJAX 将文件上传到 Spring Boot 应用程序的问题
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-07
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 2019-07-25
      • 2020-10-19
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多