Limiting upload file size – Spring
You might want to limit the size of file to be uploaded on your website as it eats up some of the bandwidth and this can cause problem to rest of the users of your site. Most of the time we do processing on files when they are uploaded on server and content validations has limitations on client side as you can not read files using javascript on client side (i.e. web browser).
Limit on upload size makes more sense for specific purposes on your website when you know about expected size of file beforehand like image upload websites etc.
If you are using Spring framework for your project/product you can do this using latest version of commons-fileupload which lets you write your own ProgressListener using which you can limit file upload size and monitor the upload process as well. We are using Ajax in our project and for file upload we are using ajaxfileupload (see more in detail)
Following things need to be done for achieving the goal:
1. Implement the ProgressListener for your application like below by implementing org.apache.commons.fileupload.progresslistener
package com.listener; import javax.servlet.http.HttpSession; import net.sf.json.JSONObject; import org.apache.commons.fileupload.ProgressListener; public class AjaxProgressListener implements ProgressListener { public static final String STATUS_UPLOADING = "UPLOADING"; public static final String STATUS_FAILED = "FAILED"; public static final String STATUS_DONE = "DONE"; public static final String STATUS_MAX_SIZE_EXCEEDS = "MAX_SIZE_EXCEEDS"; private HttpSession session; public void setSession(HttpSession session){ this.session = session; } public void updateStatus(String status){ session.setAttribute("progressStatus", status); } public void update(long bytesRead, long contentLength, int item) { JSONObject progressMap = new JSONObject(); progressMap.set("bytesRead", bytesRead); progressMap.set("contentLength", contentLength); progressMap.set("item", item); session.setAttribute("progressMap", progressMap); if(bytesRead == contentLength) { session.setAttribute("progressStatus", STATUS_DONE); } } }
Progress Listener will read the status of file upload using http request and will set a parameter map in session object so that it can be used for monitoring.
2. Extend the CommonsMultipartResolver provided by Spring framework and use the ProgressListener implemented to check the size of upload.
package com.resolver; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUpload; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import com.listener.AjaxProgressListener; public class AjaxMultipartResolver extends CommonsMultipartResolver { private AjaxProgressListener progressListener; private HttpServletRequest httpServletRequest; public void setProgressListener(AjaxProgressListener progressListener) { this.progressListener = progressListener; } public AjaxProgressListener getProgressListener() { return progressListener; } public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException { try { this.httpServletRequest = request; return super.resolveMultipart(request); } catch(MaxUploadSizeExceededException ex) { this.progressListener.updateStatus(AjaxProgressListener.STATUS_MAX_SIZE_EXCEEDS); throw new MultipartException(ex.getMessage()); } catch (Exception ex) { //exception is typically thrown when user hits stop or cancel //button halfway through upload this.progressListener.updateStatus(AjaxProgressListener.STATUS_FAILED); throw new MultipartException(ex.getMessage()); } } }
3. Update your application-beans.xml for your custom MultipartResolver written in step 2 and re-start the server.
<bean id="multipartResolver" class="com.resolver.AjaxMultipartResolver"> <property name="maxInMemorySize"> <!-- Max in memory 10kbytes --> <value>10240</value> </property> <property name="maxUploadSize"> <!-- 10 MB Max upload size --> <value>1024000000</value> </property> <!-- <property name="uploadTempDir"> <value>/tmp</value> </property> --> <property name="progressListener"> <ref bean="progressListener" /> </property> </bean> <bean id="progressListener" class="com.listener.AjaxProgressListener"/>
These values will be used for checking the file upload size and will automatically be set in AjaxMultipartResolver at the time of server start. Change these values according to your need.
Most Commented Posts
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.
Comments
hello i have implemented your progress listener but i have a question. Who calls the update method you declare in your listener, the multipart controllers does not call it unless there is an exception and there just call the update status. So how does it works
Hi Mongaru, Thanks for spending your time. You confusion is genuine. I actually missed some part of code here. You also need to add implementation of newFileUpload(FileItemFactory f) in AjaxMultipartResolver.
Following is the code:
protected FileUpload newFileUpload(FileItemFactory fileItemFactory) {
FileUpload fileUpload = super.newFileUpload(fileItemFactory);
if (progressListener != null) {
progressListener.setSession(httpServletRequest.getSession());
fileUpload.setProgressListener(this.progressListener);
this.progressListener.updateStatus(AjaxProgressListener.STATUS_UPLOADING);
}
return fileUpload;
}
fileUpload.setProgressListener(this.progressListener); is the main line which sets the listener and calls update function regularly.
That sure doesn’t look thread-safe to me. If you have multiple simultaneous uploads, isn’t it conceivable that each one will overwrite the AjaxMultipartResolver bean’s httpServletRequest instance variable?!
Hi this is an interesting article .Can you send to me the complete codes? Thanks I appreciate your help

[...] posted about how to limit the file size while uploading it recently. File upload can be a time taking process in following two [...]