例子为上传一张图片
配置multipart
使用standardServletMultipartResolver依赖于Servlet 3.0对multipart请求的支持(始于Spring 3.1)
Servlet包要配置成3.0或以上的
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
配置MultipartResolver
@Configuration
public class MultipartResolverConfig {
@Bean
public MultipartResolver multipartResolver() throws IOException{
return new StandardServletMultipartResolver();
}
}
@Import({ MultipartResolverConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter{
....
}
配置上传属性
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
.....
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
//限制文件的大小不超过2MB,整个请求不超过4MB,而且所有的文件都要写到磁盘中
String location = "d://tmp//spittr//uploads//";
registration.setMultipartConfig(new MultipartConfigElement(location,20971520, 41943040, 0));
}
.....
}
处理multipart请求
@RequestMapping(value = "/register",method=RequestMethod.POST)
public String processRegister(
@RequestPart("profilePicture") MultipartFile profilePicture) throws IOException{
String location = "d://tmp//spittr//uploads//";
profilePicture.transferTo(new File(location + profilePicture.getOriginalFilename()));
return "ok";
}
发起multipart请求
<form method="POST" enctype="multipart/form-data">
Picture:<input type="file" name="profilePicture" accept="image/jpeg,image/png,image/gif" /><br/>
<input type="submit" value="Register" />
</form>