Spring使用经验之StandardServletMultipartResolver实现文件上传的基本配置
Note:Spring使用版本是4.1.6.RELEASE
1. 在实现了AbstractAnnotationConfigDispatcherServletInitializer的类中重载customizeRegistration方法,注册MultipartConfig
public class ***WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement("D:/home/midware/tmp")); // 该目录是临时目录,必须真实存在,不然报500错误
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { MvcConfig.class };
}
}
2. 在实现了WebMvcConfigurerAdapter的类中注册StandardServletMultipartResolver
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "***" })
public class MvcConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver irViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/pages/");
resolver.setSuffix(".jsp");
resolver.setOrder(10);
return resolver;
}
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
}
3. 实现Upload的业务逻辑的Controller
@Controller
public class FileUploadController {
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(@RequestPart("file") MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException {
System.out.println(file.getContentType());
System.out.println(file.getName());
System.out.println(file.getOriginalFilename());
file.transferTo(new File("D:/home/midware/upload", file.getOriginalFilename()));// 将上传文件写入到文件系统中
return "result";
}
@RequestMapping(value = "/toupload", method = RequestMethod.GET)
public String toUpload() {
System.out.println("forward upload.jsp!");
return "upload";
}
}
4. 实现upload.jsp的页面,放在webapp/pages/下
upload.jsp包含以下内容
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload" />
</form>
5. 其他如web.xml,result.jsp等(略)