添加依赖
1 <!-- 文件上传组件 --> 2 <dependency> 3 <groupId>commons-fileupload</groupId> 4 <artifactId>commons-fileupload</artifactId> 5 <version>1.3.1</version> 6 </dependency>
配置文件中
1 <!-- 定义文件上传解析器 --> 2 <bean id="multipartResolver" 3 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 4 <!-- 设定默认编码 --> 5 <property name="defaultEncoding" value="UTF-8"></property> 6 <!-- 设定文件上传的最大值5MB,5*1024*1024 --> 7 <property name="maxUploadSize" value="5242880"></property> 8 </bean>
控制器
1 @Controller 2 @RequestMapping("/file") 3 public class FileUploadController { 4 5 @RequestMapping("/page") 6 public String page() { 7 return "fileUpload"; 8 } 9 10 @RequestMapping("/upload") 11 public String upload(@RequestParam("file") MultipartFile multipartFile) 12 throws Exception { 13 if (multipartFile != null) { 14 // multipartFile.getOriginalFilename() 获取文件的原始名称 15 multipartFile.transferTo(new File("C:\tmp\"+ multipartFile.getOriginalFilename())); 16 } 17 return "redirect:/html/success.html"; // 重定向跳转 18 } 19 20 }
页面
<form action="/file/upload.do" method="post" enctype="multipart/form-data"> 文件: <input name="file" type="file" /><br />
<input type="submit" value=" 提交 " /> </form>