本文基于注解的配置,敬请留意
一。springmvc为我们提供两种上传方式配置:
- org.springframework.web.multipart.commons.CommonsMultipartResolver (基于commons-fileupload.jar)
- org.springframework.web.multipart.support.StandardServletMultipartResolver (基于servlet3.0+)
二。配置方式基于commons-fileupload.jar
1)在先前的类DispacherConfig里添加如下代码:
1 /** 2 * 此处注意bean的名字一定起名为multipartResolver 3 * @return 4 */ 5 @Bean 6 public CommonsMultipartResolver multipartResolver() { 7 CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(); 8 commonsMultipartResolver.setDefaultEncoding(propertyConfig.getUploadDefaultEncoding()); 9 commonsMultipartResolver.setMaxUploadSize(1024 * 1024 * propertyConfig.getMaxUploadSize());//字节为单位10 return commonsMultipartResolver;11 }
注意bean的名字一定为:multipartResolver,贼恶心,曾经起别的名字死活报错
2)在先前的application.properties添加如下代码:
#注意以兆为单位spring.web.max.upload.size=30 spring.web.fileupload.encoding=utf-8
3)更改propertyConfig类添加对应的属性:
@Value("${spring.web.max.upload.size}") private Integer maxUploadSize; @Value("${spring.web.fileupload.encoding}") private String uploadDefaultEncoding="utf-8"; public String getUploadDefaultEncoding() { return uploadDefaultEncoding; } public Integer getMaxUploadSize() { return maxUploadSize; }
三。配置方式基于servlet3.0+
此时我们需要在MyWebAppInitializer里重写 customizeRegistration 方法
1 /** 2 * servlet3.0+ 上传文件 3 * 单个文件最大5M 4 * 总请求最大20M 5 * @param registration 6 */ 7 @Override 8 protected void customizeRegistration(ServletRegistration.Dynamic registration) { 9 String temp = System.getProperty("java.io.tmp");10 MultipartConfigElement multipartConfigElement = new MultipartConfigElement(temp, 5242880, 20971520, 0);11 registration.setMultipartConfig(multipartConfigElement);12 }
在DispacherConfig里添加如下bean
1 @Bean2 public MultipartResolver multipartResolver() {3 StandardServletMultipartResolver standardServletMultipartResolver = new StandardServletMultipartResolver();4 return standardServletMultipartResolver;5 }
注意bean的名字一定为:multipartResolver
如果您想通过配置实现,则需在web.xml里配置代码:
12 12dispatcher 3org.springframework.web.servlet.DispatcherServlet 41 56 110 7c:/tmp 82000000 940000000 1013 dispatcher 14*.form 15
同样需要在spring-bean里的配置:
13
四。在controller中实现文件上传
创建控制器UploadController并写相关上传代码:
1 @PostMapping("/upload") 2 public String upload(@RequestParam(name = "file")MultipartFile file) throws IOException { 3 System.out.println(file.getOriginalFilename());//获取文件名 4 FilenameUtils.getExtension(file.getOriginalFilename());//获取文件类型 5 /* 6 省略拼接文件地址代码 7 。。。 8 */ 9 file.transferTo(new File("上传目标文件地址"));10 11 return "uploadSuccess";12 }