0

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?

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.