第一步:配置sping
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!--1024*200即200k-->
- <property name="maxUploadSize" value="204800"/>
- <!--resolveLazily属性启用是为了推迟文件解析,以便在UploadAction 中捕获文件大小异常-->
- <property name="resolveLazily" value="true"/>
- </bean>
第二步:在上传action中自己捕获异常
- @RequestMapping
- public void execute(
- @RequestParam(required = false) MultipartFile file,
- @RequestParam(value = "file_info_id", required = false) Integer fileInfoId,
- ModelMap model, HttpServletRequest request) throws Exception {
- if (file == null || file.isEmpty()) {
- return;
- }
- byte[] bytes = file.getBytes();
- ……………………
- ………………
- }
- @ExceptionHandler(Exception.class)
- public ModelAndView handleException(Exception ex,HttpServletRequest request) {
- Map<Object, Object> model = new HashMap<Object, Object>();
- if (ex instanceof MaxUploadSizeExceededException){
- model.put("errors", "文件应不大于 "+
- getFileKB(((MaxUploadSizeExceededException)ex).getMaxUploadSize()));
- } else{
- model.put("errors", "不知错误: " + ex.getMessage());
- }
- return new ModelAndView("/common/file/upload", (Map) model);
- }
- private String getFileKB(long byteFile){
- if(byteFile==0)
- return "0KB";
- long kb=1024;
- return ""+byteFile/kb+"KB";
- }
- private String getFileMB(long byteFile){
- if(byteFile==0)
- return "0MB";
- long mb=1024*1024;
- return ""+byteFile/mb+"MB";
- }
第三步:界面
- <script type="text/javascript">
- $(function() {
- $('#frmupload1').submit(function() {
- if ($('#file1').val() == '') {
- alert('请选择上传导入文件!');
- $('#file1').focus();
- return false;
- }else{
- if(!isvalidatefile($('#file1').val()))
- return false;
- }
- });
- $('#frmupload2').submit(function() {
- if ($('#file2').val() == '') {
- alert('请选择上传导入文件!');
- $('#file2').focus();
- return false;
- }else{
- if(!isvalidatefile($('#file2').val()))
- return false;
- }
- });
- });
- function isvalidatefile(obj) {
- var extend = obj.substring(obj.lastIndexOf(".") + 1);
- //alert(extend);
- if (extend == "") {
- } else {
- if (!(extend == "xls" )) {
- alert("请上传后缀名为xls(Excel2003)或xlsx(Excel2007)的文件!");
- return false;
- }
- }
- return true;
- }
- <body>
- <h1>上传文件</h1>
- <form action="" method="post" enctype="multipart/form-data" onsubmit="return checkSubmit();">
- <p>请选择文件:</p>
- <p ${not empty errors ?"style='color : red;'":""}>${errors}</p>
- <input type="file" name="file" id="file"/> <input type="submit" value="确定"/>
- </form>
- </body>
网上查到的方法是:
1 使用org.springframework.web.servlet.handler.SimpleMappingExceptionResolver,如:
- <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <property name="exceptionMappings">
- <props>
- <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error/maxUploadExceeded</prop>
- </props>
- </property>
个人更赞成这种方式,因为multipartResolver通常是全局使用的,指定的maxUploadSize通常也是全局的,这里应该配置一个全局异常处理来响应。
2 自己实现.HandlerExceptionResolver类,如
- public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
- private Log log = LogFactory.getLog(getClass());
- public ModelAndView resolveException(HttpServletRequest request,
- HttpServletResponse response, Object handler, Exception ex) {
- log.warn("Handle exception: " + ex.getClass().getName());
- Map model = new HashMap();
- model.put("ex", ex.getClass().getSimpleName());
- model.put("error", ex.getMessage());
- return new ModelAndView("error", model);
- }
另定义<bean class="MyHandlerExceptionResolver "/>
扫描二维码关注公众号,回复:
334320 查看本文章
这两种方法的侵入性真的太大了,查看源代码org.springframework.web.multipart.commons.CommonsMultipartResolver 127行
- if (this.resolveLazily) {
- return new DefaultMultipartHttpServletRequest(request) {
- @Override
- protected void initializeMultipart() {
- MultipartParsingResult parsingResult = parseRequest(request);
- setMultipartFiles(parsingResult.getMultipartFiles());
- setMultipartParameters(parsingResult.getMultipartParameters());
- }
- };
- }
有个resolveLazily属性,一个类似懒加载的属性.可以定义该属性.让解析文件的时候再抛异常,然后Controller中定义异常处理的方法
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
- p:defaultEncoding="utf-8" >
- <property name="resolveLazily" value="true"/>
- <property name="maxUploadSize" value="1024" />
- </bean>
定义异常处理的方法
- @ExceptionHandler(Exception.class)
- public String handleException(Exception ex,HttpServletRequest request) {
- if(ex instanceof org.springframework.web.multipart.MaxUploadSizeExceededException){
- request.setAttribute("error", "文件超过长度");
- }
- return "要转向的页面,可以自由定义或者是原页面.";
- }