a) 得到文件保存目录的真是路径
b) 创建方法:void listFiles(File file,Map map),迭代处理所有目录及文件,将所有文件存入Map对象中,K——V uuidname——realname
c) 将Map对象写入request,传至listfiles.jsp
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到保存上传文件的文件夹 String savepath = this.getServletContext(). getRealPath("/WEB-INF/upload"); Map map = new HashMap(); //迭归文件夹下面的所有文件 迭归过程中如何保存迭归出来的数据 listFiles(new File(savepath),map); request.setAttribute("map", map); request.getRequestDispatcher("/listfile.jsp"). forward(request, response); } private void listFiles(File file,Map map) { if(file.isFile()){ String uuidname = file.getName(); String realname = uuidname. substring(uuidname.indexOf("_")+1); map.put(uuidname, realname); }else{ //得到目录下所有的文件 File files[] = file.listFiles(); for(File f: files){ listFiles(f,map); } }
取出map中的数据,并构建url作为下载链接的href属性值
<c:forEach var="me" items="${filesMap}"> <c:url var="fileAddr" value="/servlet/DownloadServlet"> <c:param name="uuidName">${me.key }</c:param> <c:param name="realName">${me.value }</c:param> </c:url> 文件名:${me.value }<a href="${fileAddr }" >下载</a><br/> </c:forEach>
显示结果如下:
a) 从request中取出文件名等信息,注意中文字符使用的urlencoding,需要进行手动编码转换。
b) 根据文件的uuidName计算出文件的存储路径
c) 判断目标文件是否存在
d) 设置response的header中的content-disposition值为attachment;filename=realName
e) 获取输入流,并写入输出流
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String uuidName = request.getParameter("uuidName"); String realName = request.getParameter("realName"); uuidName = new String(uuidName.getBytes("iso8859-1"),"utf-8"); //真实文件名取出来必须经过转码,然后因为需要作为下载链接地址,所以需要再一次转码 realName = URLEncoder.encode(new String(realName.getBytes("iso8859-1"),"utf-8"),"utf-8"); System.out.println(getFileAddr(uuidName)); File file = new File(getFileAddr(uuidName)); if(!file.exists()){ request.setAttribute("message", "下载的文件不存在!"); request.getRequestDispatcher("/message.jsp") .forward(request, response); }else{ response.setHeader("content-disposition", "attachment;filename="+realName); FileInputStream fin = new FileInputStream(file); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while((len = fin.read(buffer))>0){ out.write(buffer,0,len); } fin.close(); } } public String getFileAddr(String uuidName){ int dir1 = uuidName.hashCode() & 0xf; int dir2 = (uuidName.hashCode()>>4) & 0xf; String fileAddr = this.getServletContext().getRealPath("/WEB-INF/upload") +"\\"+ dir1+"\\" + dir2 +"\\" + uuidName; return fileAddr; }