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. 

 

 

 

  1. package com.mcw.sns.listener;

  2. import javax.servlet.http.HttpSession;

  3. import net.sf.json.JSONObject;

  4. import org.apache.commons.fileupload.ProgressListener;

  5. public class AjaxProgressListener implements ProgressListener {

  6. public static final String STATUS_UPLOADING = "UPLOADING";
  7. public static final String STATUS_FAILED = "FAILED";
  8. public static final String STATUS_DONE = "DONE";
  9. public static final String STATUS_MAX_SIZE_EXCEEDS = "MAX_SIZE_EXCEEDS";

  10. private HttpSession session;

  11. public void setSession(HttpSession session) {
  12. this.session = session;
  13. }

  14. public void updateStatus(String status) {
  15. session.setAttribute("progressStatus", status);
  16. }

  17. public void update(long bytesRead, long contentLength, int item) {
  18. JSONObject progressMap = new JSONObject();
  19. progressMap.put("bytesRead", bytesRead);
  20. progressMap.put("contentLength", contentLength);
  21. progressMap.put("item", item);
  22. session.setAttribute("progressMap", progressMap);

  23. if (bytesRead == contentLength) {
  24. session.setAttribute("progressStatus", STATUS_DONE);
  25. }
  26. }

  27. }

 

 

  1. package com.mcw.sns.resolver;

  2. import javax.servlet.http.HttpServletRequest;

  3. import org.springframework.web.multipart.MaxUploadSizeExceededException;
  4. import org.springframework.web.multipart.MultipartException;
  5. import org.springframework.web.multipart.MultipartHttpServletRequest;
  6. import org.springframework.web.multipart.commons.CommonsMultipartResolver;

  7. import com.mcw.sns.listener.AjaxProgressListener;
  8.  
  9. public class AjaxMultipartResolver extends CommonsMultipartResolver {
  10.     private AjaxProgressListener progressListener;
  11.     private HttpServletRequest httpServletRequest;
  12.  
  13.     public void setProgressListener(AjaxProgressListener progressListener) {
  14.         this.progressListener = progressListener;
  15.     }
  16.  
  17.     public AjaxProgressListener getProgressListener() {
  18.         return progressListener;
  19.     }
  20.  
  21.     public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
  22.         try {
  23.             this.httpServletRequest = request;
  24.  
  25.             return super.resolveMultipart(request);
  26.         } catch(MaxUploadSizeExceededException ex) {
  27.          this.progressListener.updateStatus(AjaxProgressListener.STATUS_MAX_SIZE_EXCEEDS);
  28.              throw new MultipartException(ex.getMessage());
  29.         } catch (Exception ex) {
  30.             //exception is typically thrown when user hits stop or cancel
  31.             //button halfway through upload
  32.             this.progressListener.updateStatus(AjaxProgressListener.STATUS_FAILED);
  33.             throw new MultipartException(ex.getMessage());
  34.         }
  35.     }
  36. }

 

  1. <bean id="multipartResolver" class="com.mcw.sns.resolver.AjaxMultipartResolver">
  2. <property name="maxInMemorySize">
  3. <!-- Max in memory 10kbytes -->
  4. <value>10240</value>
  5. </property>
  6. <property name="maxUploadSize">
  7. <!--  10 MB Max upload size -->
  8. <value>1024000000</value>
  9. </property>
  10.         
  11.         <property name="uploadTempDir">
  12. <value>D:/Temp/</value>
  13. </property>
  14. <property name="progressListener">
  15. <ref bean="progressListener" />
  16. </property>
  17. </bean>
  18.  
  19. <bean id="progressListener" class="com.mcw.sns.listener.AjaxProgressListener"/>

 

 

 

이 글은 스프링노트에서 작성되었습니다.

Posted by 이버리
,