zoukankan      html  css  js  c++  java
  • MaxUploadSizeExceededException异常

    Spring中向服务器上传图片需要进行配置bean CommonsMultipartResolver;具体配置如下:

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 默认编码 (ISO-8859-1) -->
            <property name="defaultEncoding" value="UTF-8"/>
            <!-- 最大内存大小 (10240) -->
            <property name="maxInMemorySize" value="10240"/>
            <!-- 上传后的目录名 -->
            <!--<property name="uploadTempDir" value="/upload"/>-->
            <!-- 最大文件大小,-1为无限止(-1),最大上传文件3M -->
            <property name="maxUploadSize" value="3000000"/>
        </bean>

    上面的配置中可以看到设置的文件上传的大小限制为3M;当上传的文件的大小超过上限时,便会抛出MaxUploadSizeExceededException异常。

    今天遇到的最大的问题便是:如何优雅的处理MaxUploadSizeExceededException异常?

    MaxUploadSizeExceededException异常的特殊之处在于,当上传文件的大小超过限制时,它的抛出并是在进入Controller之前,所以不能在controller中利用注解@ExceptionHandler(MaxUploadSizeExceededException.class)来定义该异常的处理方法;

    经过网上的搜索,出了利用filter以为,还看到其它三种处理办法:

    1.在xml中配置SimpleMappingExceptionResolver,其中加入对MaxUploadSizeExceededException异常的处理,指定对应的错误页面,具体如下:

    <!-- 全局异常处理 -->
        <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="exceptionMappings">
                <props>
                    <!-- 处理超过大小时的异常 -->
                    <!--遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/views/errors/upload.jsp页面 -->
                    <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">errors/upload</prop>
                </props>
            </property>
        </bean>

    2.将对应的controller实现HandlerExceptionResolver接口,然后重写其中的resolveException方法,返回ModelAndView,用于对MaxUploadSizeExceededException进行处理,具体如下:

    @Controller
    public class FileUploadController  implements HandlerExceptionResolver
    {
    
        /*** Trap Exceptions during the upload and show errors back in view form ***/
        public ModelAndView resolveException(HttpServletRequest request,
                HttpServletResponse response, Object handler, Exception exception)
        {
            Map<String, Object> model = new HashMap<String, Object>();
            if (exception instanceof MaxUploadSizeExceededException)
            {
                model.put("errors", exception.getMessage());
            } else
            {
                model.put("errors", "Unexpected error: " + exception.getMessage());
            }
            model.put("uploadedFile", new UploadedFile());
            return new ModelAndView("/upload", model);
        }
    
    }

    3.继承CommonsMultipartResolver类,重写parseRequest方法,在其中对MaxUploadSizeExceededException异常信息进行处理,放入request中,在controller再进行相应ModelAndView的返回,具体如下:

    public class DropOversizeFilesMultipartResolver extends CommonsMultipartResolver {
    
        @Override
        protected MultipartParsingResult parseRequest(final HttpServletRequest request) {
    
            String encoding = determineEncoding(request);
            FileUpload fileUpload = prepareFileUpload(encoding);
    
            List fileItems;
    
            try {
                fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            } catch (FileUploadBase.SizeLimitExceededException ex) {
                request.setAttribute(EXCEPTION_KEY, ex);
                fileItems = Collections.EMPTY_LIST;
            } catch (FileUploadException ex) {
                throw new MultipartException("Could not parse multipart servlet request", ex);
            }
    
            return parseFileItems(fileItems, encoding);
        }
    }

     

    controller
    @InitBinder("fileForm")
      protected void initBinderDesignForm(WebDataBinder binder) {
        binder.setValidator(new FileFormValidator());
      }
    
        @RequestMapping(value = "/my/mapping", method = RequestMethod.POST)
      public ModelAndView acceptFile(HttpServletRequest request, Model model, FormData formData,
          BindingResult result) {
    
        Object exception = request.getAttribute(DropOversizeFilesMultipartResolver.EXCEPTION_KEY);
        if (exception != null && FileUploadBase.SizeLimitExceededException.class.equals(exception.getClass())) {
          result.rejectValue("file", "<your.message.key>");
          LOGGER.error(exception);
        }

    以上三种方法都能够类似实现返回一个ModelAndView来实现对MaxUploadSizeExceededException进行处理;


    http://stackoverflow.com/questions/2689989/how-to-handle-maxuploadsizeexceededexception

    http://stackoverflow.com/questions/4029583/using-spring-3-exceptionhandler-with-commons-fileupload-and-sizelimitexceededex

  • 相关阅读:
    类似详情表里面查询最后一次下的订单(以下示例是查找最近一次登陆的记录)
    你真的理解了继承和多态吗?
    尝试了N个版本的Visual C++ 2005后,终于这个Visual C++ 2005 Express Beta 2可以用了。
    [Eclipse笔记]请对Java、Sun、NetBeans、Eclipse感兴趣朋友的看看Eclipse对Sun的心态吧
    [Eclipse笔记]无意中发现Eclipse3.1M7中增加的一项虽然小却很方便的功能
    [Eclipse笔记]Back to the old days Eclipse下的二进制文件编辑器插件EHEP
    [Eclipse笔记]Eclipse3.1M7在Windows下新的内存管理方式
    Is JBuilder dead?
    [Eclipse笔记]SQLExplorer插件试用手记
    [Eclipse笔记]Bug 21493 fixed
  • 原文地址:https://www.cnblogs.com/userrain/p/5433233.html
Copyright © 2011-2022 走看看