qccaprospect
qccaprospect

Reputation: 151

XHR Multipart File Upload Spring Boot Issue

I have an upload progress bar that works upon file input and when the bar reaches 100%, there is no error. But as I print the contents of the file in Spring Boot, I notice that the code within the for loop does not run. Here is the code. Please help and thank you!

JavaScript:

function upload(file) {
    var formData = new FormData();
    formData.append("newFile", file);
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/upload');
    xhr.onload = function(e) {
        console.log("xhr onload function");
    };
    var progressBar = document.querySelector('progress');
    xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
            progressBar.value = (e.loaded / e.total) * 100;
            progressBar.textContext = progressBar.value;
        }
    };
    xhr.send(formData);
}

Spring Boot:

@RequestMapping(value="/upload", method=RequestMethod.POST)
public String upload(@RequestParam("files") MultipartFile[] files) {

    // This prints [Lorg.springframework.web.multipart.MultipartFile;@........].
    System.out.println(files);
    for (MultipartFile file : files) {
        // This doesn't get printed.
        System.out.println(file.getOriginalFilename());
    }
    return "redirect:/";
}

Upvotes: 0

Views: 980

Answers (2)

user9065831
user9065831

Reputation:

In JavaScript you are adding file to ‘newFile’ variable but on spring side you are extracting file from request param ‘files’.

Are you uploading multiple files? It doesn’t seems so. Try only with Multipart.

Upvotes: 1

GnanaJeyam
GnanaJeyam

Reputation: 3170

Because MultipartFile[] files were just initialized but does not contain any array of values.

Change the

public String upload(@RequestParam("files") MultipartFile[] files)

to

public String upload(@RequestPart(value = "files", required = true) MultipartFile[] files)

Upvotes: 1

Related Questions