1.需要的jar包,路径:/WebContent/WEB-INF/lib
2.在springMVC的配置文件中进行文件上传下载的配置。/WebContent/WEB-INF/springmvc-config.xml
<!-- 文件上传的配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
<property name="maxUploadSize" value="200000"/>
</bean>
<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到WebContent目录下的error.jsp页面 -->
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error</prop>
</props>
</property>
</bean>
注:那个error页面,我不知道那样的写法对不对,或者是只能放在webcontent下,如果是放在别的路径,不知是否是在这里设置。因为没有遇到过上传错误所以也无法进行验证。
3. 写jsp页面。/WebContent/WEB-INF/jsp/upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="upload.do" enctype="multipart/form-data" accept-charset="utf-8">
文件1: <input type="file" name="myfiles"/><br/>
文件2: <input type="file" name="myfiles"/><br/>
文件3: <input type="file" name="myfiles"/><br/>
<input type="submit" value="上传">
</form>
</body>
</html>
注:enctype=”multipart/form-date”是必须要写的。
此外还要创建一个uploadSuccess.jsp和一个error.jsp
4.写controller。/src/com.guozi.controller/UpLoadController.class
@RequestMapping("/upload")
public String upload(@RequestParam MultipartFile[] myfiles,HttpServletRequest request) throws IOException {
//设置编码格式
request.setCharacterEncoding("UTF-8");
for(MultipartFile file : myfiles){
//此处MultipartFile[]表明是多文件,如果是单文件MultipartFile就行了
if(file.isEmpty()){
System.out.println("文件未上传!");
}
else{
//得到上传文件的文件名,并且在之前加上当前时间形成唯一文件名,解决文件上传重名的问题
Calendar ca=Calendar.getInstance();
String fileName ="("+ ca.get(Calendar.YEAR)+(ca.get(Calendar.MONTH)+1)+ca.get(Calendar.DATE)+ca.get(Calendar.HOUR_OF_DAY)+ca.get(Calendar.MINUTE)+ca.get(Calendar.SECOND)+")"+file.getOriginalFilename();
//上传文件的路径,先得到项目在服务器上的路径再在后边加上文件名,其中/WEB-INF/images是把上传文件保存在项目WEB-INF文件夹下images文件夹里的,假如images不存在,系统会自动创建一个images文件夹
String rootPath= request.getSession().getServletContext().getRealPath("/WEB-INF/images/"+fileName);
System.out.println("文件名:"+fileName);
System.out.println("路径:"+rootPath);
// //把文件上传至path的路径
File localFile = new File(rootPath);
file.transferTo(localFile);
}
return "uploadSuccess";
}
return "error";
}
注:由于在jsp页面设置了enctype=”multipart/form-date”,导致得到的文件名出现中文乱码,按照网上的说法设置jsp或者server.xml的编码格式,或者是转码等方式都没有解决,继续探索下去发现两种解决乱码的方式:我用的方式B
A.不用form传值,改用juery ajax传值,绕过enctype=”multipart/form-date”的设置。
B.在项目的配置文件中加上以下代码;
<filter>
<filter-name>Encoding</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
5.测试。由于我们的jsp放到WEB-INF/jsp下的,所以不能直接访问到,要通过controller来访问(只有放在WebContent或WEB-INF下才能直接访问,我也不知道为啥),所以我们还要在/src/com.guozi.controller/UpLoadController.class写上以下代码:
@RequestMapping("/up")
public String up(){
return "upload";
}
然后运行tomcat。在浏览器输入:http://localhost:8080/HelloWorddd/up.do(helloworddd是项目名)。
点击上传之后跳转到uploadSuccess.jsp页面,那文件到底在服务器上了吗。我们一开始把得到的项目在服务器上的路径输出到控制台。所以根据控制台的路径去看看文件在不在那里。
看了下在那里,说明上传成功了。
注:路径要写对,上传要去看下文件在不在那里,我在项目中出现原来建的文件夹变成无格式文件,上传的文件找不到的情况,后来发现是上传路径把文件夹给覆盖了。
下载
1.新建一个下载页面downLoad.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="download.do?fileName=3132.jpg">下载</a>
</body>
</html>
2./src/com.guozi.controller/UpLoadController.class
@RequestMapping("/download")
public String download(String fileName, HttpServletRequest request,
HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
try {
//路径
String path=request.getSession().getServletContext().getRealPath("/WEB-INF/images/");
System.out.println(path);
InputStream inputStream = new FileInputStream(new File(path+fileName));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 返回值要注意,要不然就出现下面这句错误!
//java+getOutputStream() has already been called for this response
return null;
}
3.测试,controller加上以下代码
@RequestMapping("/down")
public String down(){
return "downLoad";
}
浏览器路径:http://localhost:8080/HelloWorddd/down.do
结果:下载成功
参考文章:http://blog.csdn.net/qq_32953079/article/details/52290208