接上一篇:异常解析器+拦截器
1. 导入jar包
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
<exclusions>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
</exclusion>
</exclusions>
</dependency>
其中的exclusions是排除servlet-api的jar包,因为已经导入过了
2. 表单
fileupload.jsp
<body>
<form action="${pageContext.request.contextPath}/file/test" method="post" enctype="multipart/form-data">
<input type="file" name="source"/><br/>
<input type="submit" value="上传"/>
</form>
</body>
3. Controller
- 上面input的name=“source”要与调用的方法里的参数名(MultipartFile )source对应
- WEB-INF目录下新建upload目录
- 注意upload目录下必须要有一个文件,不然不能加载到测试目录target下
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/test")
public String test(MultipartFile source, HttpSession session) throws IOException {
//获取文件名
String originalFilename = source.getOriginalFilename();
//生成一个唯一的文件名
String uniqueFilename = UUID.randomUUID().toString().replaceAll("-","")+originalFilename;
//获取上传文件路径
String realPath = session.getServletContext().getRealPath("/upload");
//保存文件
source.transferTo(new File(realPath+"\\"+uniqueFilename));
return "index";
}
}
4. 上传解析器
- mvc.xml文件中配置
- 上传解析器的id必须是:multipartResolver,如果不写或者不是这个,springMVC就找不到上传解析器,文件上传失败
<!--上传解析器
id必须是这个,如果不写或者不是这个,springMVC就找不到上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--最大可上传的文件大小,单位:byte,超出后会抛出MaxUploadSizeExceededException异常,可以被异常解析器捕获-->
<property name="maxUploadSize" value="1048576"></property>
</bean>
- 最大可上传的文件大小,单位:byte,超出后会抛出MaxUploadSizeExceededException异常
如果直接在上传解析器中添加<property name=“maxUploadSize” value=“1048576”></property>,在运行过程中不会报错,只会没有上传,所以我们用拦截器+异常处理器的方式来捕获文件大小超出限制的错误,并跳转到相应的uploadError.jsp页面
下面注释掉该行代码:
4.1 拦截器
- 新建interceptor包,新建类:MyFileuploadInterceptor.java
- 实现HandlerInterceptor接口,重写preHandler()方法
- 属性值maxFileuploadSize给set方法,在mvc.xml给value值为=“10485765
public class MyFileuploadInterceptor implements HandlerInterceptor {
private Long maxFileuploadSize;
public void setMaxFileuploadSize(Long maxFileuploadSize) {
this.maxFileuploadSize = maxFileuploadSize;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ServletRequestContext servletRequestContext = new ServletRequestContext(request);
long l = servletRequestContext.contentLength();
if(l>maxFileuploadSize){
throw new MaxUploadSizeExceededException(maxFileuploadSize);
}
return true;
}
}
- mvc.xml文件中配置
<!--拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/file/test"/>
<bean class="com.lyx.interceptor.MyFilenameInterceptor">
<property name="maxFileuploadSize" value="1048576"></property>
</bean>
</mvc:interceptor>
</mvc:interceptors>
4.2 异常解析器
- 新建resolver包,新建类MyFileUploadExceptionResolver
public class MyFileUploadExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView modelAndView = new ModelAndView();
if(ex instanceof MaxUploadSizeExceededException){
modelAndView.setViewName("redirect:/uploadError.jsp");
}
return modelAndView;
}
}
- mvc.xml文件中配置
<!--异常解析器-->
<bean class="com.lyx.resolver.MyFileUploadExceptionResolver"></bean>
5. Tomcat运行
访问http://localhost:8080/fileupload.jsp
- 注意上传的文件只能在target目录下查看