文章目录
Servlet后台处理请求
@WebServlet( urlPatterns= {"/FileDownloadServlet"} )
public class FileDownloadServlet extends HttpServlet{
private String dirPath = "C:\\Users\\lrc\\Desktop\\Java-Web项目";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String parent = req.getParameter("fileName");
String currentPath = dirPath;
String lastCatalog = req.getParameter("lastCatalog");
if("1".equals(lastCatalog)) {
parent = parent.substring(0, parent.lastIndexOf("/"));
System.out.println(parent);
currentPath = currentPath + "/" + parent;
File file = new File(currentPath);
req.setAttribute("files", file.listFiles());
req.setAttribute("parent", parent);
}else if(parent==null || "".equals(parent.trim())) {
File file = new File(currentPath);
File[] files = file.listFiles();
req.setAttribute("files", files);
}else {
currentPath = currentPath + "/" + parent;
File file = new File(currentPath);
if(file.isFile()) {
InputStream is = new FileInputStream(file);
System.out.println(file.getName());
resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
OutputStream os = resp.getOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len = is.read(buffer))!=-1) {
os.write(buffer, 0, len);
}
return;
}else {
File[] files = file.listFiles();
req.setAttribute("files", files);
req.setAttribute("parent", parent);
}
}
req.getRequestDispatcher("/FIleDownload.jsp").forward(req, resp);
}
}
JSP处理前端页面显示
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/" />
<title>Insert title here</title>
</head>
<body>
<table border="1">
<thead>
<tr>
<th>资源名</th>
<th>资源大小</th>
</tr>
<thead>
<tbody>
<c:if test="${not empty parent}">
<tr>
<td colspan="2" align="center"><a href="FileDownloadServlet?fileName=${parent}&lastCatalog=1">...上一级</a></td>
</tr>
</c:if>
<c:forEach items="${files}" var="file">
<tr>
<td><a href="FileDownloadServlet?fileName=${parent}/${file.name}">${file.name}</a></td>
<td>${file.length()}字节</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
效果显示
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-B3eUg4cn-1576003320444)(en-resource://database/12387:1)]](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5df49093f05348e7ac06fe42756fed78~tplv-k3u1fbpfcp-jj-mark:3024:0:0:0:q75.image)
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UnaWXJ1l-1576003320447)(en-resource://database/12389:1)]](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b64aead0a5c141feb3932be329586bef~tplv-k3u1fbpfcp-jj-mark:3024:0:0:0:q75.image)