1 使用注解方式初始化Spring MVC
WebConfig.java
@Configuration
@EnableWebMvc
@ComponentScan("com.wu.controller")
public class WebConfig {
@Bean
public ViewResolver initViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
/**
* 配置Multipart解析器(用于解析文件上传)
*/
@Bean
public MultipartResolver initMultipartResolver() {
return new StandardServletMultipartResolver();
}
}
MyWebAppInitializer.java
/**
* 使用这个类就可以完成Spring MVC配置,而不用web.xml文件
*/
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"*.do"};
}
/**
* 对文件上传进行一些参数配置
* @param registration
*/
@Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
super.customizeRegistration(registration);
String location = "e:/mvc/uploads/"; // 文件存储地址
long maxFileSize = 10*1000*1000; // 单个文件最大尺寸
long maxRequestSize = 2*maxFileSize; // 上传的所有文件的最大尺寸
registration.setMultipartConfig(new MultipartConfigElement(location, maxFileSize, maxRequestSize, 0));
}
}
2 实现代码
2.1 上传文件页面:
<form action="./file/upload.do" method="post" enctype="multipart/form-data">
<input type="file" name="file" value="请选择上传的文件" />
<input type="submit" value="提交" />
</form>
2.2 文件上传控制器
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/upload")
public ModelAndView upload(MultipartFile file) {
ModelAndView mv = new ModelAndView();
String filename = file.getOriginalFilename();
File dest = new File(filename);
try{
file.transferTo(dest);
mv.addObject("msg", "文件上传成功");
}catch (Exception e) {
mv.addObject("msg", "文件上传失败");
e.printStackTrace();
}
mv.setViewName("info");
return mv;
}
}
2.3 测试结果
注: 这里上传带有中文文件名的文件时,保存的文件名会出现乱码。