jiachunguo1234
哥特式悲伤
采纳率0%
2015-05-01 14:51

Springmvc上传文件限制大小,异常处理返回报错信息后,eclipse控制台还报错

1、web.xml配置:

 <?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">


<!-- 注册主控制器DispatcherServlet -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定spring配置文件位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.from</url-pattern>
</servlet-mapping>

<!-- 指定读取所有文件的编码格式 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

    </web-app>

spring的applicationContext.xml配置:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 定义自动扫描组件 -->
    <context:component-scan base-package="controller"></context:component-scan>

    <!-- 定义@RequestMapping映射的注解驱动 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 定义视图解析器 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <!-- 注册spring web mvc中处理上传事件的组件CommonsMultipartResolver,
        而具体怎样处理上传文件,则是由导入的包common-upload.jar和common-io.jar去处理-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10240"></property>
        <property name="resolveLazily" value="true"></property>
    </bean>
</beans>

java代码Controller处理:

 package controller;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UploadController {

    // 访问upload.jsp页面
    @RequestMapping("/toUpload")
    public String toUpload() {
        return "upload";
    }

    @RequestMapping("/upload")
    public String upload(@RequestParam("file")
    MultipartFile file, HttpServletRequest request, ModelMap model)
            throws Exception {

        // 判断提交来的文件是否为空
        if (file.isEmpty()) {
            // model.addAttribute("error", "上传文件不能为空");
            // return "upload";
            throw new RuntimeException("file is null");
        }
        // 获取文件所要保存目录在服务器上所对应的实际路径
        String path = request.getSession().getServletContext().getRealPath(
                "upload");
        System.out.println(path);
        // 组成拥有真实路径的一个完整的地址字符串
        String fileUrl = path + "\\" + file.getOriginalFilename();
        // 封装上传文件名称到model对象中
        model.addAttribute("fileName", file.getOriginalFilename());
        // 根据这个完整地址字符串,生成提交文件所要保存到的目标文件或目录的对象
        File targetFile = new File(fileUrl);
        // 判断目标文件或目录的对象是否已经存在
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        // 传送文件到目标对象

        file.transferTo(targetFile);

        System.out.println("已上传文件:" + file);
        return "ok";
    }

    @ExceptionHandler
    public ModelAndView doException(Exception e,HttpServletRequest request) throws Exception {
        Map<String,Object> map = new HashMap<String,Object>(); 
        if (e instanceof MaxUploadSizeExceededException) {
            long maxSize = ((MaxUploadSizeExceededException) e)
                    .getMaxUploadSize();
            map.put("error", "上传文件太大,不能超过" + maxSize / 1024 + "k");
        }else if(e instanceof RuntimeException){
            map.put("error", "未选中文件");
        }else{
            map.put("error", "上传失败");
        }
        return new ModelAndView("upload",map);

    }
}


上传文件页面upload.jsp:

 <%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>上传页面</title>
  </head>

  <body>
    <form action="upload.from" method="post" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="submit" value="上传"/><font color="red">${error}</font>
    </form>
  </body>
</html>

上传成功页面ok.jsp:

 <%@ page pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>ok.jsp</title>
  </head>

  <body>
   <h1>上传成功</h1>
   <a href="upload/${fileName}">${fileName}</a>
  </body>
</html>

eclipse控制台报错信息如下:

 五月 01, 2015 10:27:01 下午 org.springframework.web.multipart.commons.CommonsMultipartResolver cleanupMultipart
警告: Failed to perform multipart cleanup for servlet request
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size of 10240 bytes exceeded; nested exception is org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (19243) exceeds the configured maximum (10240)
    at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:160)
    at org.springframework.web.multipart.commons.CommonsMultipartResolver$1.initializeMultipart(CommonsMultipartResolver.java:131)
    at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultipartFiles(AbstractMultipartHttpServletRequest.java:119)
    at org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest.getMultiFileMap(AbstractMultipartHttpServletRequest.java:99)
    at org.springframework.web.multipart.commons.CommonsMultipartResolver.cleanupMultipart(CommonsMultipartResolver.java:188)
    at org.springframework.web.servlet.DispatcherServlet.cleanupMultipart(DispatcherServlet.java:1062)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:955)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2476)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2465)
    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: org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (19243) exceeds the configured maximum (10240)
    at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:914)
    at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
    at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:349)
    at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
    at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
    ... 37 more

上传文件超过限制大小,异常处理后页面返回了提示信息“上传文件太大,不能超过10k”,但是为啥eclipse的控制台还是有报错呢?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • code2code code2code 6月前

    通信协议限制了数据传送量。
    我用的是weblogic。
    首先控制台⇒AdminServer的设置⇒协议里更改【最大消息大小】
    另外客户端程序也要做修改
    方法1(自己试过ok):
    然后在你的应用程序里加上下面代码。
    System.setProperty("weblogic.MaxMessageSize", "20000000");
    方法2(没试过,别人的贴子)
    You can also set the value in your JAVA_OPTIONS -Dweblogic.MaxMessageSize=300000000

    点赞 评论 复制链接分享
  • xiangduole2044676867 大白菜鸟 5年前

    tomcat会出现这个问题,使用jetty不会有问题

    点赞 评论 复制链接分享
  • frankcheng5143 GW_Cheng 5年前

    我也是,在springmvc中配置了,为什么不能捕获异常,请问楼主解决了吗?

    点赞 评论 复制链接分享
  • wodemusic 寻找W宝石 5年前

    我也遇到这个问题了 ,在springmvc中配置了,就无法铺货异常了,请问有好的解决办法吗?

    点赞 评论 复制链接分享
  • rjcs888 liuaoz 5年前

    今天也碰到一样的问题了,有什么办法解决吗

    点赞 评论 复制链接分享