suchen

Heim  >  Fragen und Antworten  >  Hauptteil

java - Spring Boot怎么处理上传文件时出现的MultipartException

在config中配置了文件的大小

@Configuration
public class CommonConfig {

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize(1024L * 1024L);
        return factory.createMultipartConfig();
    }
}

当文件的大小超出设置值时,返回500错误

org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
    at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:111)
    at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:85)
    at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:76)
    at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1091)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:930)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:87)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
15:24:27.612 [http-nio-8080-exec-1] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Invoking @ExceptionHandler method: public void com.bsd.article.manager.controller.ExceptionController.exceptionHandler(java.lang.Exception,javax.servlet.http.HttpServletResponse) throws java.io.IOException
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
15:24:27.615 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
15:24:27.615 [http-nio-8080-exec-1] DEBUG o.s.web.servlet.DispatcherServlet - Successfully completed request
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
    at org.apache.catalina.connector.Request.parseParts(Request.java:2846)
    at org.apache.catalina.connector.Request.parseParameters(Request.java:3151)
    at org.apache.catalina.connector.Request.getParameter(Request.java:1108)
    at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:380)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:70)
    ... 22 more
Caused by: org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 1048576 bytes.
    at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl$FileItemStreamImpl$1.raiseError(FileUploadBase.java:633)
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.checkLimit(LimitedInputStream.java:76)
    at org.apache.tomcat.util.http.fileupload.util.LimitedInputStream.read(LimitedInputStream.java:135)
    at java.io.FilterInputStream.read(FilterInputStream.java:107)
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:98)
    at org.apache.tomcat.util.http.fileupload.util.Streams.copy(Streams.java:68)
    at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:293)
    at org.apache.catalina.connector.Request.parseParts(Request.java:2776)
    ... 26 more
    

需要怎么做才能返回200的友好提示?

PHP中文网PHP中文网2769 Tage vor961

Antworte allen(2)Ich werde antworten

  • PHPz

    PHPz2017-04-18 09:45:10

    拦截这个异常:

    @ControllerAdvice
    public class ExceptionProcess {
        // 对这个异常的统一处理,返回值 和Controller的返回规则一样
        @ExceptionHandler(MultipartException.class)
        public String handleAll(Throwable t){
            // TODO do sth
            return "view";
        }
    }

    Antwort
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:45:10

    1、文件上传大小可在js框架里就做验证了。推荐JS上传框架uploadify.js
    2、既然使用了springboot,那你的文件上传的处理应该在Controller里处理。
    3、如果你需要的仅仅是错误信息跳转到错误页面而不是打印堆栈信息,只需要实现一个@RequestMapping(value = "/error")的Controller实现。
    4、给你一个springboot实现上传的小demo,可借鉴。

    /**
     * Created by Projack
     * 上传视图
     */
    @Controller
    @RequestMapping(value = "/admin/file")
    public class FileController {
    
        @Value("${images.domain.url}")
        private String IMAGES_DOMAIN_URL;
        @Value("${images.localhost.url}")
        private String IMAGES_LOCALHOST_URL;
    
        //获取分隔符(不同系统不同)
        String sep = System.getProperty("file.separator");
    
        /**
         * 上传文件到七牛服务器
         * @param file
         * @return
         */
        @RequestMapping(value = "/upload")
        @ResponseBody
        public String upload(@RequestParam(value="file", required=false) MultipartFile file){
            String imgPath = "";
            try{
                String fileName = file.getOriginalFilename();
                String localPath = IMAGES_LOCALHOST_URL + sep + fileName;
                FileCopyUtils.copy(file.getBytes(), new File(localPath));     //图片保存本地服务器
                imgPath = QiNiuUtils.upload(localPath);                       //图片上传七牛云服务器
                FileSystemUtils.deleteRecursively(new File(localPath));      //删除本地服务器的图片
                imgPath = IMAGES_DOMAIN_URL + "/" + imgPath;
            }catch(Exception e){
                e.printStackTrace();
            }
            return imgPath;
        }
    
        /**
         * 删除文件到七牛服务器
         * @param fileName
         */
        @RequestMapping(value = "/delete")
        public void delete(String fileName){
            QiNiuUtils.delete(fileName);
        }
    

    }

    Antwort
    0
  • StornierenAntwort