JavaWeb之文件下载
一、概述
1. 下载就是向客户端响应字节数据!
原来我们响应的都是html的字符数据!
把一个文件变成字节数组,使用response.getOutputStream()来各应给浏览器!!!
2. 下载的要求
* 两个头一个流!
> Content-Type:你传递给客户端的文件是什么MIME类型,例如:image/pjpeg
* 通过文件名称调用ServletContext的getMimeType()方法,得到MIME类型!
> Content-Disposition:它的默认值为inline,表示在浏览器窗口中打开!attachment;filename=xxx
* 在filename=后面跟随的是显示在下载框中的文件名称!
> 流:要下载的文件数据!
* 自己new一个输入流即可!
二、通过Servlet下载1
被下载试玩资源放到WEB-INF目录下,(只要用户不能通过浏览器直接访问就OK)然后通过Servlet完成下载
在JSP页面给出超链接,链接到DownloadServlet,并提供要下载的文件名称。然后DownloadServlet获取文件的真实路径,然后把文件写入到response.getOutputStream()流中。
download.jsp
1 2 3 4 5 6 7 | <body> This is my JSP page. <br> <a href="<c:url value='/DownloadServlet?path=a.avi'/>">a.avi</a><br/> <a href="<c:url value='/DownloadServlet?path=a.jpg'/>">a.jpg</a><br/> <a href="<c:url value='/DownloadServlet?path=a.txt'/>">a.txt</a><br/> </body> |
DownloadServlet
1 2 3 4 5 6 7 8 9 10 11 12 | public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = request.getParameter("path"); String filepath = this.getServletContext().getRealPath("/WEB-INF/uploads/" + filename); File file = new File(filepath); if(!file.exists()) { response.getWriter().print("您要下载的文件不存在!"); return; } IOUtils.copy(new FileInputStream(file), response.getOutputStream()); } |
上面代码有如下问题
1,可以下载a.aiv,但在下载框中的文件名称是DownloadServlet
2,不能下载a.jsp和a.txt,而是在页面中显示他们
三、通过Servlet下载2
下面来处理上一例中的问题,让下载框中可以显示正确的文件名称,以及可以下载a.jpg和a.txt文件。
通过添加content-disposition头来处理上面问题。当设置了content-disposition头后,浏览器就会弹出下载框。
而且还可以通过content-disposition头来指定下载文件的名称!
1 2 3 4 5 6 7 8 9 10 | String filename = request.getParameter("path"); String filepath = this.getServletContext().getRealPath("/WEB-INF/uploads/" + filename); File file = new File(filepath); if(!file.exists()) { response.getWriter().print("您要下载的文件不存在!"); return; } response.addHeader("content-disposition", "attachment;filename=" + filename); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); |
虽然上面的代码已经可以处理txt和jpg等文件的下载问题,并且也处理了在下载框中显示文件名称的问题,但是如果下载的文件名称是中文的,那么还是不行的。
四、通过Servlet下载3
下面是处理在下载框中显示中文的问题
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | String filename = request.getParameter("path"); // GET请求中,参数中包含中文需要自己动手来转换。 // 当然如果你使用了“全局编码过滤器”,那么这里就不用处理了 filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8"); String filepath = this.getServletContext().getRealPath("/WEB-INF/uploads/" + filename); File file = new File(filepath); if(!file.exists()) { response.getWriter().print("您要下载的文件不存在!"); return; } // 所有浏览器都会使用本地编码,即中文操作系统使用GBK // 浏览器收到这个文件名后,会使用iso-8859-1来解码 filename = new String(filename.getBytes("GBK"), "ISO-8859-1"); response.addHeader("content-disposition", "attachment;filename=" + filename); IOUtils.copy(new FileInputStream(file), response.getOutputStream()); |