SpringMVC为文件上传提供了直接支持,这种支持是通过即插即用MultipartResolver实现的。
Spring中有一个MultipartResolver实现类:CommonsMultipartResolver
Spring上下文中默认没有装配MultipartResolver,因此默认情况下不能处理文件上传工作。想要使用上传功能,需要在上下文中装配MultipartResolver。
1.1、添加依赖
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
@Controller@RequestMapping("file")public class FileController { @RequestMapping("upload") public String upload(@RequestParam("myFile")MultipartFile myFile, HttpServletRequest request){ String originalFilename = myFile.getOriginalFilename(); String fileName = UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf(".")); System.out.println(fileName); String realPath=request.getServletContext().getRealPath("/uploadFile")+"/"; try { myFile.transferTo(new File(realPath+fileName)); System.out.println("上传成功"+realPath+fileName); } catch (IOException e) { e.printStackTrace(); } return "ok"; } @RequestMapping("hello") public String hello(){ return "/jsp/fileHandle"; } }
1.5、限制文件类型1、添加过滤器 FileInterceptor
public class FileInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { boolean result=true; //判断是否是文件上传请求 if(request instanceof MultipartHttpServletRequest){ //获取文件对象map MultipartHttpServletRequest multipartRequest= (MultipartHttpServletRequest) request; Map
2、配置过滤器到springmvc.xml
3、添加上传错误页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
@RequestMapping("download") public ResponseEntity