实现文件下载的步骤:
- 定位系统中的哪些文件需要用户下载
- 将需要下载的文件放入指定目录中
- 开发一个页面,提供一个文件下载连接
- 开发下载控制器controller
页面
<h1>文件下载</h1>
<a href="${pageContext.request.contextPath}/file/download?fileName=img.png">img.png</a>
控制器
@RequestMapping("/download")
public void download(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("下载文件的名称: " + fileName);
String realPath = request.getSession().getServletContext().getRealPath("/down");
FileInputStream is = new FileInputStream(new File(realPath, fileName));
response.setContentType("text/plain;charset=utf-8");
response.setHeader("content-disposition", "attachment;fileName=" + fileName);
ServletOutputStream os = response.getOutputStream();
int len;
byte[] b = new byte[1024];
while (true) {
len = is.read(b);
if (len == -1) {
break;
}
os.write(b, 0, len);
}
is.close();
os.close();
}
文件下载加强版【直接打开,以附件的形式下载】
<h1>文件下载</h1>
<ul>
<li>img.png<a href="${pageContext.request.contextPath}/file/download?fileName=img.png">在线打开</a> <a href="${pageContext.request.contextPath}/file/download?fileName=img.png&openStyle=attch">附件下载</a></li>
<li>img.png<a href="${pageContext.request.contextPath}/file/download?fileName=aa.jpg">在线打开</a> <a href="${pageContext.request.contextPath}/file/download?fileName=aa.jpg&openStyle=attch">附件下载</a></li>
<li>img.png<a href="${pageContext.request.contextPath}/file/download?fileName=自我介绍.txt">在线打开</a> <a href="${pageContext.request.contextPath}/file/download?fileName=自我介绍.txt&openStyle=attch">附件下载</a></li>
</ul>
@RequestMapping("/download")
public void download(String openStyle,String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
openStyle = openStyle == null ? "inline" : "attachment";
System.out.println("下载文件的名称: " + fileName);
String realPath = request.getSession().getServletContext().getRealPath("/down");
FileInputStream is = new FileInputStream(new File(realPath, fileName));
response.setContentType("text/plain;charset=utf-8");
response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(fileName, "utf-8"));
ServletOutputStream os = response.getOutputStream();
IOUtils.copy(is, os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
|