怎么使用Servlet 3.0中的上传文件呢?

Spring 3.1开始提供了Servlet 3.0的支持。不过对于上传文件的文档却说得很不清楚,不过在stackoverflow的帮助下,我终于搞明白怎么用了。

首先,你得先配置dispatcher servlet的参数,使得其支持文件上传:

ServletRegistration.Dynamic servlet = container.addServlet("spring-dispatcher", new DispatcherServlet(context)); // 就是这一句 servlet.setMultipartConfig(new MultipartConfigElement("/tmp")); servlet.setLoadOnStartup(1); servlet.addMapping("/");

 

然后在spring配置文件中配置一个multipartResolver

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver" />

 

再然后就是你的代码了:

@RequestMapping(value = "/upload", method = RequestMethod.GET) public String fillUploadForm() { return "upload"; } @RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleUploadForm(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { logger.info(String.format("name: %s, file name: %s", name, file.getOriginalFilename())); return "redirect:index"; }

你可能感兴趣的:(servlet)