Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring MVC multiple files upload

Tags:

spring-mvc

jsp

I'm using spring MVC and JSP. I want to upload 2 files, issue is only one file is getting uploaded. Below is the code:

<form id="myform" name="myform" action="/createRequest.htm" enctype="multipart/form-data" method="POST">
//form elements like textbox, checkbox
    <tr>
        <th class="RelReqstAllign"></th><td> (Or)<input type="file" name="fileUpload" size="50"/></td>
    </tr>
    <tr>
        <th class="RelReqstAllign"></th><td><input type="file" name="fileUpload" size="50" /></td>
    </tr>
</form>

Below is the spring controller code:

@RequestMapping(value = "/createRequest", method = RequestMethod.POST)
public ModelAndView createRequest(final HttpServletRequest request,
        final HttpServletResponse response,
        final @ModelAttribute("spRequestDTO") SPRequestDTO dto,
        final BindingResult beException,
        final @RequestParam("buttonName") String buttonName,
        @RequestParam CommonsMultipartFile[] fileUpload) throws IOException {
    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload) {

            System.out.println("Saving file: "
                    + aFile.getOriginalFilename());

            if (!aFile.getOriginalFilename().equals("")) {
                try {
                    aFile.transferTo(new File(saveDirectory + aFile.getOriginalFilename()));
                } catch (IllegalStateException e) {

                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }
    }
}

When I debug the controller, fileUpload is showing only one file, even when I upload two files.

Below is the code added in Spring-mvc.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
like image 657
user3684675 Avatar asked Mar 20 '23 11:03

user3684675


2 Answers

Just do like this. you dont need to have more than input tag in your form to select multiple files

  <input type="file" name="fileUpload" size="50" multiple/>    

It will allow users to select multiple files in their sytem by clicking ctrl option in keyboard.

And then, in your action class, do your stuff as you wanted.

Make sure fileUpload variable as file array in your bean class

like image 96
user3662273 Avatar answered Apr 06 '23 03:04

user3662273


I had a similar problem a few weeks ago and I could not get the handler method handle multiple MultipartFiles. As a solution I injected the HttpServletRequest and casted it to DefaultMultipartHttpServletRequest to be able to access all files.

List<MultipartFile> files = ((DefaultMultipartHttpServletRequest) request)
    .getFiles("fileUpload");
like image 39
Bart Avatar answered Apr 06 '23 02:04

Bart