maven增加配置:
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency>
springmvc.xml 增加配置:
<!-- 上传文件需要的配置 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="1024000"></property> </bean>
页面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <h2>Hello World !</h2> <a href="home/show" target="_blank">打开一个mvc页面</a> <br/> <form action="home/fileUpload" method="POST" enctype="multipart/form-data"> 姓名:<input type="text" name="uname" value="张三"/> <br/> 文件: <input type="file" name="file1"/> <br/> <input type="submit" value="上传文件"/> </form> </body> </html>
控制器:
package com.shuoeasy.springmvc; import java.io.File; import java.io.IOException; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @RequestMapping("/home") @Controller public class Home { /** * 路径 : home/show * @throws IOException */ @RequestMapping("/fileUpload") public String fileUpload( @RequestParam("uname") String uname, @RequestParam("file1") MultipartFile file) throws IOException{ System.out.println("uname=" + uname); System.out.println("fileName=" + file.getOriginalFilename()); System.out.println("InputStream=" + file.getInputStream()); // 保存文件 save(file); return "home_index"; } private void save(MultipartFile file) throws IllegalStateException, IOException{ File targetFile = new File("D:/tmp", file.getOriginalFilename()); if(!targetFile.exists()){ targetFile.mkdirs(); file.transferTo(targetFile); } } }