0

I need to load an unknown number of files at once. I found an example, and it works for a known amount of files:

markup:

<form  method="POST" enctype="multipart/form-data">
<input name="files[0]" type="file" />
<input name="files[1]" type="file" />
<input type="submit" value="Send"/>
</form>

code:

@RequestMapping(method = RequestMethod.POST)
public String savePhoto(@ModelAttribute("album") Album album,  BindingResult result, SessionStatus status,  MultiPartFileUploadBean file) 
{
    List<MultipartFile> images = file.getFiles();
    for (MultipartFile photo : images) {
    ...     
    }
    return "redirect:/albums/"+album.getId();
}

MultiPartFileUploadBean:

public class MultiPartFileUploadBean {
    private List<MultipartFile> files;

    public void setFiles(List<MultipartFile> files) {
        this.files = files;}

    public List<MultipartFile> getFiles() {
        return files;}
}

Yes, it works, but I do not know how the user wants to upload a photo in the album. And I use:

<input name="files[]" type="file" multiple="multiple" />

I'll get a error.

Request processing failed; nested exception is java.lang.NumberFormatException: For input string: ""

I was looking for how to use multiple = "multiple", but found none. I hope for your help.

user3387180
  • 1
  • 1
  • 1
  • 1
    `files[]` isn't a proper name remove the `[]`. – M. Deinum Mar 06 '14 at 09:07
  • OK. I corrected. But now after selecting the files loaded only the first of the list. – user3387180 Mar 06 '14 at 09:19
  • See http://stackoverflow.com/questions/15726439/how-to-upload-multiple-files-using-one-file-input-element. In short you will have a use a fully HTML5 capably browser else it will not work with `multiple`. – M. Deinum Mar 06 '14 at 09:21

1 Answers1

6

In your XHTML:

<input name="files" type="file" multiple="multiple" />

Alter the request-mapped method:

@RequestMapping(method = RequestMethod.POST)
public String savePhoto(MultipartRequest multipartRequest, ...)
{
    List<MultipartFile> images = multipartRequest.getFiles("files");
    ...
}
holmis83
  • 15,922
  • 5
  • 82
  • 83