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>
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
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With