**
文件下载
**
代码
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
String realPath = request.getServletContext().getRealPath("/WEB-INF/upload");
System.out.println(realPath);
String filename = request.getParameter("filename");
String s = filename.split("_")[1];
System.out.println(s);
String storage = UUIDFile.storage(s, realPath);
response.setHeader("content-disposition","attachment;filename="+URLEncoder.encode(s,"UTF-8"));
FileInputStream is=new FileInputStream(storage+"\\"+filename);
System.out.println(storage+"\\"+filename);
ServletOutputStream sos = response.getOutputStream();
int len=0;
byte[] bytes=new byte[1024*1024*100];
while ((len=is.read(bytes))!=-1){
sos.write(bytes,0,len);
}
is.close();
sos.close();
}
文件UUID路径与源文件名获取
public static void GetFile(File file, HashMap<String,String> list){
//返回file文件下所有文件与目录的文件名,返回File数组
File[] files=file.listFiles();
for(File file1:files){
//file1.isDirectory判断时候为文件夹
if(file1.isDirectory()){
//递归查找
GetFile(file1,list);
}else {
String name = file1.getName();
//以“_”作为分割符
int i = name.indexOf("_");
//(i+1)是因为分割后是有下滑线的向前一位去掉下滑线
String substring = name.substring(i + 1);
//name为UUDI路径名,substring:源文件名
list.put(name,substring);
}
}
}
将HashMap类容发向前端
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
HashMap<String,String> map=new HashMap<>(16);
String realPath = req.getServletContext().getRealPath("/WEB-INF/upload");
SelectFile.GetFile(new File(realPath),map);
req.setAttribute("files",map);
req.getRequestDispatcher("/list.jsp").forward(req,resp);
}
前端类容
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table>
<tr>
<th></th>
<th></th>
</tr>
<c:forEach items="${files}" var="entry">
<tr>
<th>${entry.value}</th>
<th><a href="${pageContext.request.contextPath}/downLoad?filename=${entry.key}">下载</a></th>
</tr>
</c:forEach>
</table>
</body>
</html>