SpringMVC-文件下载

文件下载

文件下载很简单,只要设置一下响应头即可

页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<style>
ul li {
cursor: pointer;
}
</style>
</head>
<body>
<a href="javascript:">点击文字下载</a>
<ul id="ul">
<c:forEach items="${fileList}" var="file">
<li><a href="/fileDownLoad.do?fileName=${file}">${file}</a></li>
</c:forEach>
</ul>
</body>
</html>

Controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@GetMapping("/fileDownLoad.do")
public String fileDownLoad(String fileName,HttpServletRequest req,HttpServletResponse resp) throws IOException {
String realPath = req.getServletContext().getRealPath("\\download")+"\\";
File file = new File(realPath.concat(fileName));
resp.setHeader("Content-disposition","attachment; filename="+ URLEncoder.encode(file.getName(),"UTF-8"));
ServletOutputStream outputStream = resp.getOutputStream();
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len=0;
while((len=fis.read(buffer))>0){
outputStream.write(buffer,0,len);
}
outputStream.flush();
fis.close();
outputStream.close();
return "filedownload";
}

给作者买杯咖啡吧~~~