Jsp+Servlet实现文件上传下载(四)--下载文件
接着上一篇讲:
Jsp+Servlet实现文件上传下载(三)--删除上传文件 点击打开链接
Jsp+Servlet实现文件上传下载(三)--删除上传文件 点击打开链接
本章来实现一下下载文件功能,同时优化了一下上一章中的代码。
废话少说,上代码
--------------------------------------------------------分割线---------------------------------------------------------------------------------
调整列表页面list.jsp,增加下载链接
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>上传文件列表</title>
</head>
<body>
<h3>文件列表</h3>
<table class="acclist_tab" border="1" bordercolor="#000000" cellspacing="0" cellpadding="2" style="border-collapse:collapse;">
<tr>
<th>文件名</th>
<th>文件大小(KB)</th>
<th>操作</th>
</tr>
<c:if test="${not empty accessoryList}">
<c:forEach items="${accessoryList}" var="acc">
<tr>
<td>${acc.fileName}</td>
<td>${acc.fileSize}</td>
<td>
<a href="<%=request.getContextPath()%>/removeUploadedFile?id=${acc.id}">删除</a>
<a href="<%=request.getContextPath()%>/downloadUploadedFile?id=${acc.id}">下载</a>
</td>
</tr>
</c:forEach>
</c:if>
</table>
</body>
</html>
新增下载文件控制器:DownloadUploadedFileServlet
package servlet.upload;
import dao.upload.AccessoryDao;
import entity.upload.EntityAccessory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
/**
* 下载文件控制器
*
* @author xusucheng
* @create 2017-12-30
**/
@WebServlet("/downloadUploadedFile")
public class DownloadUploadedFileServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//拿到文件ID
int fileId = Integer.valueOf(request.getParameter("id"));
EntityAccessory entity = AccessoryDao.load(fileId);
String filePath = entity.getFilePath();
String fileName = entity.getFileName();
String errorMessage = "";
//判断文件是否存在
File file = new File(filePath);
if (file.exists()) {
//设置响应头
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//创建文件输入流
FileInputStream is = new FileInputStream(filePath);
//创建输出流
OutputStream os = response.getOutputStream();
//创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
//写数据到浏览器
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
//关闭流
is.close();
os.close();
} else {
errorMessage = "下载失败,文件:" + filePath + " 不存在";
request.setAttribute("errorMessage", errorMessage);
request.getRequestDispatcher("pages/upload/error.jsp").forward(request, response);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
优化了上一章servlet类名,调整为大写开头了
项目结构图
测试效果截图
下载失败提示:
下集预告
敬请期待。