spring mvc CommonsMultipartResolver文件上传maxUploadSize限制大小

第一步:配置sping 

Xml代码   收藏代码
  1. <bean id="multipartResolver"  
  2.           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  3.         <!--1024*200即200k-->  
  4.         <property name="maxUploadSize" value="204800"/>  
  5.         <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->  
  6.         <property name="resolveLazily" value="true"/>    
  7.     </bean>  


第二步:在上传action中自己捕获异常 

Java代码   收藏代码
  1.  @RequestMapping  
  2.     public void execute(  
  3.             @RequestParam(required = false) MultipartFile file,  
  4.             @RequestParam(value = "file_info_id", required = false) Integer fileInfoId,  
  5.             ModelMap model, HttpServletRequest request) throws Exception {  
  6.               
  7.         if (file == null || file.isEmpty()) {  
  8.             return;  
  9.         }  
  10.         byte[] bytes = file.getBytes();  
  11.             ……………………  
  12. ………………  
  13. }  
  14.   @ExceptionHandler(Exception.class)         
  15.     public ModelAndView handleException(Exception ex,HttpServletRequest request) {       
  16.          Map<Object, Object> model = new HashMap<Object, Object>();  
  17.          if (ex instanceof MaxUploadSizeExceededException){  
  18.                         model.put("errors""文件应不大于 "+  
  19.                        getFileKB(((MaxUploadSizeExceededException)ex).getMaxUploadSize()));  
  20.                      } else{  
  21.                         model.put("errors""不知错误: " + ex.getMessage());  
  22.                     }  
  23.          return new ModelAndView("/common/file/upload", (Map) model);  
  24.                   
  25.     }    
  26.       
  27.     private String getFileKB(long byteFile){  
  28.         if(byteFile==0)  
  29.            return "0KB";  
  30.         long kb=1024;  
  31.         return ""+byteFile/kb+"KB";  
  32.     }  
  33.     private String getFileMB(long byteFile){  
  34.         if(byteFile==0)  
  35.            return "0MB";  
  36.         long mb=1024*1024;  
  37.         return ""+byteFile/mb+"MB";  
  38.     }  


第三步:界面 

Html代码   收藏代码
  1. <script type="text/javascript">  
  2. $(function() {  
  3.     $('#frmupload1').submit(function() {  
  4.         if ($('#file1').val() == '') {  
  5.             alert('请选择上传导入文件!');  
  6.             $('#file1').focus();  
  7.             return false;  
  8.         }else{  
  9.             if(!isvalidatefile($('#file1').val()))  
  10.                   return false;  
  11.                   
  12.         }  
  13.     });  
  14.     $('#frmupload2').submit(function() {  
  15.         if ($('#file2').val() == '') {  
  16.             alert('请选择上传导入文件!');  
  17.             $('#file2').focus();  
  18.             return false;  
  19.         }else{  
  20.             if(!isvalidatefile($('#file2').val()))  
  21.                   return false;  
  22.                   
  23.         }  
  24.     });  
  25. });  
  26.   
  27. function isvalidatefile(obj) {  
  28.       
  29.     var extend = obj.substring(obj.lastIndexOf(".") + 1);  
  30.     //alert(extend);  
  31.     if (extend == "") {  
  32.     } else {  
  33.         if (!(extend == "xls" )) {  
  34.             alert("请上传后缀名为xls(Excel2003)或xlsx(Excel2007)的文件!");  
  35.               
  36.             return false;  
  37.         }  
  38.     }  
  39.     return true;  
  40. }  
  41. <body>  
  42. <h1>上传文件</h1>  
  43. <form action="" method="post" enctype="multipart/form-data" onsubmit="return checkSubmit();">  
  44.   
  45.     <p>请选择文件:</p>  
  46.       
  47.     <p ${not empty errors ?"style='color : red;'":""}>${errors}</p>  
  48.     <input type="file" name="file" id="file"/>&nbsp;<input type="submit" value="确定"/>  
  49. </form>  
  50. </body>

网上查到的方法是:

1 使用org.springframework.web.servlet.handler.SimpleMappingExceptionResolver,如:

 

[html] 
view plain
copy

 

 
  1. <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
  2.     <property name="exceptionMappings">  
  3.    <props>  
  4.         <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error/maxUploadExceeded</prop>  
  5.    </props>   
  6. </property>  

个人更赞成这种方式,因为multipartResolver通常是全局使用的,指定的maxUploadSize通常也是全局的,这里应该配置一个全局异常处理来响应。

自己实现.HandlerExceptionResolver类,如

[java] 
view plain
copy

 

 
  1. public class MyHandlerExceptionResolver implements HandlerExceptionResolver {  
  2.     private Log log = LogFactory.getLog(getClass());  
  3.     public ModelAndView resolveException(HttpServletRequest request,  
  4.             HttpServletResponse response, Object handler, Exception ex) {  
  5.         log.warn("Handle exception: " + ex.getClass().getName());  
  6.                 
  7.         Map model = new HashMap();  
  8.         model.put("ex", ex.getClass().getSimpleName());  
  9.         model.put("error", ex.getMessage());  
  10.         return new ModelAndView("error", model);  
  11.     }  

另定义<bean class="MyHandlerExceptionResolver "/>

 

这两种方法的侵入性真的太大了,查看源代码org.springframework.web.multipart.commons.CommonsMultipartResolver 127行

 

[java] 
view plain
copy

 

 
  1. if (this.resolveLazily) {  
  2.             return new DefaultMultipartHttpServletRequest(request) {  
  3.                 @Override  
  4.                 protected void initializeMultipart() {  
  5.                     MultipartParsingResult parsingResult = parseRequest(request);  
  6.                     setMultipartFiles(parsingResult.getMultipartFiles());  
  7.                     setMultipartParameters(parsingResult.getMultipartParameters());  
  8.                 }  
  9.             };  
  10.         }  

有个resolveLazily属性,一个类似懒加载的属性.可以定义该属性.让解析文件的时候再抛异常,然后Controller中定义异常处理的方法

 

[html] 
view plain
copy

 

 
  1. <bean id="multipartResolver"  
  2.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  
  3.         p:defaultEncoding="utf-8" >  
  4.       <property name="resolveLazily" value="true"/>  
  5.       <property name="maxUploadSize" value="1024" />  
  6.     </bean>  

定义异常处理的方法

 

[java] 
view plain
copy

 

 
  1. @ExceptionHandler(Exception.class)       
  2.     public String handleException(Exception ex,HttpServletRequest request) {     
  3.         if(ex instanceof org.springframework.web.multipart.MaxUploadSizeExceededException){  
  4.             request.setAttribute("error""文件超过长度");  
  5.         }  
  6.         return "要转向的页面,可以自由定义或者是原页面.";  
  7.     }  

猜你喜欢

转载自a562509724.iteye.com/blog/2281676