Upload multiple files in Spring MVC 3

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

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

Proxy objects in Spring are not evil

Firstly, let me give some back-ground about Spring Transaction Management. Spring uses Proxies for transaction management and these proxies are JDK dynamic proxies. However, Spring uses CGLIB proxies when a bean class doesn’t implement an interface. A point to note, proxy as such delegates control to a transaction manager to manage transactions.

To understand how proxies are used in Spring, refer to Micheal Isvy’s blog.

A month ago, i was discussing with a colleague about the performance problems with proxying which is used left, right and center in Spring’s transaction management and other features. As i am a strong supporter of Spring, i couldn’t agree but at the same time couldn’t disagree with him. However, i am ready to take a stand now:

a. Proxies do add a performance over-head. A direct call to a method in target object always takes less time than a call through a proxy object.  However, it is negligible compared to the benefits we reap out of a ready-to-use features without having to worry about writing code to do it.

b. The advice above, needs to be taken with a pinch of salt, though. Too much proxying results in performance problems. A better solution in such a situation would be to perform byte code weaving using AspectJ. This is achieved by using JavaAgent.

Courtesy: Alef Arendenson

 

Purpose of ContextLoaderListener – Spring MVC

When we are working with Spring MVC and are also using Spring in the services layer, we provide two application-contexts. The first one is configured using ContextLoaderListener and the other with DispatcherServlet. A sample configuration in web.xml is mentioned below:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>    
        /WEB-INF/config/applicationContext-service.xml
        /WEB-INF/config/applicationContext-dao.xml
    </param-value>
</context-param>
<servlet>
    <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/config/servlet-context.xml
           ***/WEB-INF/config/applicationContext.xml***
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

After reading the Spring documentation, following is the understanding:

a) Application-Contexts are hierarchial and so are WebApplicationContexts. Refer documentation here.

b) ContextLoaderListener creates a root web-application-context for the web-application and puts it in the ServletContext. This context can be used to load and unload the spring-managed beans ir-respective of what technology is being used in the controller layer(Struts or Spring MVC).

c) DispatcherServlet creates its own WebApplicationContext and the handlers/controllers/view-resolvers are managed by this context.

d) When ContextLoaderListener is used in tandem with DispatcherServlet, a root web-application-context is created first as said earlier and a child-context is also created by DispatcherSerlvet and is attached to the root application-context. Refer documentation here.

Refer to the diagram below from the Spring documentation.