Spring MVC 3: Upload multiple files
It was just another long day at office with the database not available and one of the team members lagging by a week now. So, we had to work as a team to get it delivered. In Spring 3, it looked straight forward to upload a file. However, there was little help on offer, to upload multiple files from a jsp file.
There are three basic things which need to be done to upload multiple files are:
a) The JSP needs to have the input[file] elements passed as an array.
1 2 | < td >< input name = "fileData[0]" id = "image0" type = "file" /></ td > < td >< input name = "fileData[1]" id = "image1" type = "file" /></ td > |
b) The ModelAttribute/Model object in Spring MVC needs to have a list of MultipartFile.
1 2 3 4 5 | import java.util.List; import org.springframework.web.multipart.commons.CommonsMultipartFile; public class UploadItem { private String filename; private List<CommonsMultipartFile> fileData; |
c) Configure Multipart Resolver bean in dispatcher-servlet.xml[applicationContext-servlet.xml]
1 2 3 | <!-- Configure the multipart resolver --> < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > </ bean > |
d) Logic to read the files from the Model and store it in a file location in the Controller layer.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | @RequestMapping (method = RequestMethod.POST) public String create(UploadItem uploadItem, BindingResult result, HttpServletRequest request, HttpServletResponse response, HttpSession session) { if (result.hasErrors()) { for (ObjectError error : result.getAllErrors()) { System.err.println( "Error: " + error.getCode() + " - " + error.getDefaultMessage()); } return "/uploadfile" ; } // Some type of file processing... System.err.println( "-------------------------------------------" ); try { for (MultipartFile file:uploadItem.getFileData()){ String fileName = null ; InputStream inputStream = null ; OutputStream outputStream = null ; if (file.getSize() > 0 ) { inputStream = file.getInputStream(); if (file.getSize() > 20000 ) { System.out.println( "File Size exceeded:::" + file.getSize()); return "/uploadfile" ; } System.out.println( "size::" + file.getSize()); fileName = request.getRealPath( "" ) + "/images/" + file.getOriginalFilename(); outputStream = new FileOutputStream(fileName); System.out.println( "fileName:" + file.getOriginalFilename()); int readBytes = 0 ; byte [] buffer = new byte [ 10000 ]; while ((readBytes = inputStream.read(buffer, 0 , 10000 )) != - 1 ) { outputStream.write(buffer, 0 , readBytes); } outputStream.close(); inputStream.close(); // .......................................... session.setAttribute( "uploadFile" , file.getOriginalFilename()); } //MultipartFile file = uploadItem.getFileData(); } } catch (Exception e) { e.printStackTrace(); } return "redirect:/forms/uploadfileindex" ; } |
I have extended the example which is found @ RoseIndia to dynamically create the file nodes and post them to the Controller.
Just download the source-code and replace the below jsp file and make other necessary changes:
Upload.jsp
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | <% @page contentType= "text/html;charset=UTF-8" %> <% @page pageEncoding= "UTF-8" %> <%@ page session= "false" %> <html> <head> <META http-equiv= "Content-Type" content= "text/html;charset=UTF-8" > <title>Upload Example</title> <script language= "JavaScript" > var count= 0 ; function add(type) { //Create an input type dynamically. var table = document.getElementById( "fileUploadTable" ); var tr = document.createElement( "tr" ); var td = document.createElement( "td" ); var element = document.createElement( "input" ); //Assign different attributes to the element. element.setAttribute( "type" , "file" ); element.setAttribute( "value" , "" ); element.setAttribute( "name" , "fileData[" +type+ "]" ); //Append the element in page (in span). td.appendChild(element); tr.appendChild(td); table.appendChild(tr); } function Validate() { var image =document.getElementById( "image" ).value; if (image!= '' ){ var checkimg = image.toLowerCase(); if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.jpeg|\.JPEG)$/)){ alert( "Please enter Image File Extensions .jpg,.png,.jpeg" ); document.getElementById( "image" ).focus(); return false ; } } return true ; } </script> </head> <body> <form:form modelAttribute= "uploadItem" name= "frm" method= "post" enctype= "multipart/form-data" onSubmit= "return Validate();" > <fieldset><legend>Upload File</legend> <table > <tr> <input type= "button" name= "Add Image" onclick= "add(count++)" value= "Add Image" /> </tr> <tr> <table id= "fileUploadTable" > <!--td><form:label for = "fileData" path= "fileData" >File</form:label><br /> </td> <td><input name= "fileData[0]" id= "image0" type= "file" /></td> <td><input name= "fileData[1]" id= "image1" type= "file" /></td--> </table> </tr> <tr> <td><br /> </td> <td><input type= "submit" value= "Upload" /></td> </tr> </table> </fieldset> </form:form> </body> </html> |
UploadItem.java, generate getter and setter methods for the private List fileData;, UploadFileController.java and then just copy and paste the create(…) mentioned in the blog above.
Note: If you are still facing issue with file upload in Spring MVC, please add a MultipartFilter. Refer here.
1 2 3 4 5 6 7 8 | < filter > < filter-name >multipartFilter</ filter-name > < filter-class >org.springframework.web.multipart.support.MultipartFilter</ filter-class > </ filter > < filter-mapping > < filter-name >multipartFilter</ filter-name > < url-pattern >/springrest/*</ url-pattern > </ filter-mapping > |
1 2 3 4 5 | < bean id = "filterMultipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > < property name = "maxUploadSize" > < value >10000000</ value > </ property > </ bean > |
Reference: Upload multiple files in Spring MVC 3 from our JCG partner Srinivas Ovn at the Bemused blog.
This is nice one.
http://www.aspdotnet-pools.com/2014/06/multiple-file-upload-with-aspnet-mvc-c.html