首页 > WEB开发 > 后台开发 > 文件上传
2014
08-30

文件上传

4、文件下载

描述:做完上面的文件上传后,上传几张图片。最后将这些图片用一个列表列出来,并提供下载链接。

① ShowAllFilesServlet:遍历文件上传的根目录,将带UUID的文件名和老文件名存入一个map,并转到fileList.jsp进行显示。

public void doGet(HttpServletRequest request, HttpServletResponse response)	throws ServletException, IOException {
	//文件存放根目录
	String storeDirectory = getServletContext().getRealPath("/WEB-INF/files");
	File root = new File(storeDirectory);
	Map<String ,String> map = new HashMap<String,String>();
	//遍历根目录,并将带UUID的文件名和老文件名存入map集合中
	treeWalk(root,map);
	//将请求转发到文件列表页面
	request.setAttribute("map", map);
	request.getRequestDispatcher("/fileList.jsp").forward(request, response);
}

② fileList.jsp

<h1>图片列表</h1>
<c:forEach items="${map}" var="me" varStatus="vs">
	<c:url value="/servlet/FileDownloadServlet" var="downurl">
		<c:param name="filename" value="${me.key}"></c:param>
	</c:url>
	${vs.count}:${me.value} <a href="${downurl}">下载</a><br />
</c:forEach>

③ FileDownloadServlet:处理文件下载请求

public void doGet(HttpServletRequest request, HttpServletResponse response)	throws ServletException, IOException {
	//得到带UUID的文件名,并计算出老的文件名
	String uuidFileName = request.getParameter("filename");
	uuidFileName = new String(uuidFileName.getBytes("ISO-8859-1"),"utf-8");
	String oldFileName = uuidFileName.substring(uuidFileName.indexOf("_")+1);
	//用同样的方式算到文件的路径
	String filePath = mkChildDir(uuidFileName);

	//构建输入流、输出流
	InputStream in = new FileInputStream(getServletContext().getRealPath("/WEB-INF/files"+filePath+"/"+uuidFileName));
	OutputStream out = response.getOutputStream();
	//通知客户端已下载的方式打开
	response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(oldFileName, "utf-8"));

	int len = 0;
	byte[] b = new byte[1024];
	while((len = in.read(b)) != -1){
		out.write(b, 0, len);
	}
	in.close();
	out.close();
}

留下一个回复

你的email不会被公开。