项目的格式
1.显示有哪些文件能下载,展示下载文件的列表。
2.下载具体的文件。
显示列表
首先肯定是要遍历文件夹,找到能下载的文件,我们可以创建一个获得文件的工具类。
工具类:
//遍历能下载的文件,key:保存带有uuid的文件名,value保存不带uuid的文件名
public static void listFile(File dir, HashMap<String,String> map) {
File[] files = dir.listFiles();
if(files != null && files.length>0) {
for (File file : files) {
if(file.isDirectory()) {
listFile(file, map);
}else {
//文件
String uuidFileName = file.getName();
String filename = uuidFileName.substring(uuidFileName.indexOf("_") + 1);
map.put(uuidFileName,filename);
}
}
}
}
ListFileServlet:
@WebServlet(name = "ListFileServlet", value = "/listFile")
public class ListFileServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//读取可以下载的文件
//得到文件存储的根路径
String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
File file = new File(realPath);
HashMap<String,String> fileMap = new HashMap<>();
//从根路径往下遍历
UploadUtils.listFile(file, fileMap);
//存到request的域中
request.setAttribute("fileMap", fileMap);
//转发
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
list.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<body>
<h2>下载列表</h2>
<c:forEach var="entry" items="${fileMap}">
<c:url var="myurl" value="/download" >
<c:param name="filename" value="${entry.key}"></c:param>
</c:url>
<li><a href="${myurl}"><c:out value="${entry.value}"></c:out></a></li>
</c:forEach>
</body>
下载具体的文件
文件下载:
@WebServlet(name = "DownLoadServlet", value="/download")
public class DownLoadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//获得uuidfilename比如25194b8ad0a44481988d4ea58c58fd4c_p2.jpg
String filename = request.getParameter("filename");
//获得_之后的文件名。p2.jpg
String newFilename = filename.substring(filename.indexOf("_")+1);
//获取文件路径,因为上传的时候是通过这样生成的路径,所以下载也要找到这个路径
String newPath = UploadUtils.makeNewPath(request.getServletContext().getRealPath("/WEB-INF/upload"), filename);
//设置浏览器的编码格式
response.setContentType("text/html;charset=utf-8");
//这个就是文件的整个路径。
File file = new File(newPath+File.separator+filename);
if(file.exists()){
//设置响应头,表示下载
response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(newFilename, "utf-8"));
//获取输出流
ServletOutputStream writer = response.getOutputStream();
//输入流
FileInputStream reader = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while((len=reader.read(bytes))!=-1){
writer.write(bytes,0,len);
}
}else {
response.getWriter().write("该文件不存在...");
}
}