Enterprise Java

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.

<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.

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]

<!-- 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.

@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

<%@page contentType="text/html;charset=UTF-8"%>
<%@page pageEncoding="UTF-8"%>
<%@ page session="false"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>

<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.

<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>
<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.

Srinivas Ovn

Srinivas is a Senior Software Engineer in java and all related technologies. He has varied experience working in domains like finance, security and telecom. His hobbies include blogging and exploring new java frameworks/technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button