单文件上传:
pom.xml:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
upload.jsp:
1.input的type设置为file。
2.form表单的method设置为post。(get请求只会将文件名传给后台)
3.form表单的enctype设置为multipart/form-data,以二进制的形式传输数据。
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<form action="<c:url value="/upload"/>" method="post" enctype="multipart/form-data">
<input type="file" name="img">
<input type="submit" name="提交">
</form>
<br/>
<c:if test="${filePath!=null }">
<h1>上传的图片</h1><br/>
<img width="300px" src="<%=basePath %>${filePath}"/>
</c:if>
FileController.java:
@RequestMapping(value="upload", method = RequestMethod.POST)
public String upload(@RequestParam(value="img")MultipartFile img, HttpServletRequest request)
throws Exception {
//getSize()方法获取文件的大小来判断是否有上传文件
if (img.getSize() > 0) {
//获取保存上传文件的file文件夹绝对路径
String path = request.getSession().getServletContext().getRealPath("file");
//获取上传文件名
String fileName = img.getOriginalFilename();
File file = new File(path, fileName);
img.transferTo(file);
//保存上传之后的文件路径
request.setAttribute("filePath", "file/"+fileName);
System.out.println("file/"+fileName);
return "upload";
}
return "error";
}
springMVC.xml:
<!-- 配置CommonsMultipartResolver bean,id必须是multipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 处理文件名中文乱码 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 设置多文件上传,总大小上限,不设置默认没有限制,单位为字节,1M=1*1024*1024 -->
<property name="maxUploadSize" value="1048576"/>
<!-- 设置每个上传文件的大小上限 -->
<property name="maxUploadSizePerFile" value="1048576"/>
</bean>
<!-- 设置异常解析器 -->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="defaultErrorView" value="/error.jsp"/>
</bean>
注意:这里需要在webapp文件下手动创建一个file文件夹。
多文件上传:
uploads.jsp:
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<form action="uploads" method="post" enctype="multipart/form-data">
file1:<input type="file" name="imgs"><br />
file2:<input type="file" name="imgs"><br />
file3:<input type="file" name="imgs"><br />
<input type="submit" name="提交">
</form>
<c:if test="${filePaths!=null }">
<h1>上传的图片</h1><br />
<c:forEach items="${filePaths }" var="filePath">
<img width="300px" src="<%=basePath %>${filePath}"/>
</c:forEach>
</c:if>
FileController.java:
@RequestMapping(value="/uploads", method = RequestMethod.POST)
public String uploads(@RequestParam MultipartFile[] imgs, HttpServletRequest request)throws Exception {
//创建集合,保存上传后的文件路径
List<String> filePaths = new ArrayList<String>();
for (MultipartFile img : imgs) {
if (img.getSize() > 0) {
String path = request.getSession().getServletContext().getRealPath("file");
String fileName = img.getOriginalFilename();
File file = new File(path, fileName);
filePaths.add("file/"+fileName);
img.transferTo(file);
}
}
request.setAttribute("filePaths", filePaths);
return "uploads";
}
文件下载:
download.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>
<a href="download?fileName=logo.jpg">下载图片</a>
</body>
</html>
FileController.java:
@RequestMapping("/download")
public void downloadFile(String fileName,HttpServletRequest request,
HttpServletResponse response){
if(fileName!=null){
//获取file绝对路径
String realPath = request.getServletContext().getRealPath("file/");
File file = new File(realPath,fileName);
OutputStream out = null;
if(file.exists()){
//设置下载完毕不打开文件
response.setContentType("application/force-download");
//设置文件名
response.setHeader("Content-Disposition", "attachment;filename="+fileName);
try {
out = response.getOutputStream();
out.write(FileUtils.readFileToByteArray(file));
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(out != null){
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}