需要的两个jar包:
com.springsource.org.apache.commons.fileupload-1.2.0.jar、
com.springsource.org.apache.commons.io-1.4.0.jar、
web.xml
配置springmvc,url-pattern中写 *.do 、
spring-mvc.xml
除了配置使用注解的包和视图解析器之外、要支持文件上传需要加一个bean、
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="10000000"/> <!-- 最大上传字节 10M -->
</bean>
FileUploadController
//单文件上传、
@RequestMapping("/upload")
public String uploadFile(@RequestParam("file1") MultipartFile file1,HttpServletRequest request)throws Exception{ //前端有个name=file1的上传控件
String filePath=request.getServletContext().getRealPath("/"); //取项目路径
//查看此处输出的路径、在开发环境中,Tomcat是作为eclipse的一个插件、上传到插件的tmp目录去了、但是取的时候不会有影响、
System.out.println(filePath);
//把一个文件输出到指定目录
file1.transferTo(new File(filePath+"upload/"+file1.getOriginalFilename()));
return "redirect:success.html";
}
//多文件上传、用数组接收
@RequestMapping("/upload2")
public String uploadFiles(@RequestParam("file") MultipartFile[] files,HttpServletRequest request)throws Exception{
String filePath=request.getServletContext().getRealPath("/");
System.out.println(filePath);
for(MultipartFile file:files){ //遍历files数组
//实际开发中文件需要重新命名 比如当前日期的字符串(自己写工具类),此处是得到上传时的文件名
file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));
}
return "redirect:success.html";
}
index.html
<!-- —————————单文件上传————————— -->
<form action="upload.do" method="post" enctype="multipart/form-data"><!-- enctype="multipart/form-data上传文件 -->
<input type="file" name="file1"/>
<!-- —————————多文件上传————————— -->
<form action="upload2.do" method="post" enctype="multipart/form-data">
<input type="file" name="file"/> <!-- 将该语句复制多个到table中 -->