说明:关于SpringMVC框架的搭建请参照之前写过的一篇博客http://blog.csdn.net/liqingwei168/article/details/79137801
本篇文章是在上次的基础上进行增加的功能。
1. pom.xml 首先要确保上传的依赖包
<!-- 上传组件包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.9</version> </dependency>2.spring-mvc.xml文件中的配置
<!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 默认编码 --> <property name="defaultEncoding" value="utf-8" /> <!-- 文件大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 内存中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean>
3.完成上面的功能后我们就可以开始写代码了,为了方便就不分层次了,直接在Controller层中写了
创建文件 UploadController.java文件
package com.zpkj.space.controller; import com.zpkj.space.service.UpLoadService; import org.springframework.beans.factory.annotation.Autowired; 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; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; @Controller @RequestMapping("upload") public class UpLoadController { @Autowired private UpLoadService upLoadService; @RequestMapping("toUpFileMore") public String toUpFileMore(){ return "upload/listMore"; } @RequestMapping("upFileMore") public String upFileMore(@RequestParam("file") MultipartFile file[],HttpServletRequest request){ //如果文件不为空 if (file.length>0) { for(int i = 0;i<file.length;i++){ String oldFileName = file[i].getOriginalFilename(); String realPath="D:/db/"+new SimpleDateFormat("yyyy/MM/dd/hh/mm/ss").format(new Date())+"/"+ UUID.randomUUID().toString().replaceAll("-", ""); File f = new File(realPath); if(!f.exists()){ f.mkdirs();//如果目录不存在,创建目录 } try { file[i].transferTo(new File(realPath+File.separator+oldFileName));//把文件写入目标文件地址 //可以在这完成数据库路径的存储 } catch (Exception e) { e.printStackTrace(); return "error"; } } return "upload/listMore";//返回到成功页面 }else { return "error";//返回到失败的页面 } } }4. listMore.jsp前台页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head> <title>上传下载功能在线调试</title> </head> <form method="post" action="/upload/upFileMore" enctype="multipart/form-data"> <input type="file" name="file"/><br> <input type="file" name="file"/> <button type="submit" >提交</button> </form> <body> </body> </html>5.到此我们的多文件上传功能就完成了