Servlet 下载文件
Posted ai-xiaocai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Servlet 下载文件相关的知识,希望对你有一定的参考价值。
服务器端有以下文件:
首先,建一个download.html页面(在点击下载的时候,将要下载的文件名传递给服务器端):
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Insert title here</title> 6 </head> 7 <body> 8 <h1>文件下载</h1> 9 <a href="/Zhan_Web_Servlet/filedownload?filename=a.flv">a.flv</a><br> 10 <a href="/Zhan_Web_Servlet/filedownload?filename=a.jpg">a.jpg</a><br> 11 <a href="/Zhan_Web_Servlet/filedownload?filename=a.mp3">a.mp3</a><br> 12 <a href="/Zhan_Web_Servlet/filedownload?filename=a.mp4">a.mp4</a><br> 13 <a href="/Zhan_Web_Servlet/filedownload?filename=a.txt">a.txt</a><br> 14 <a href="/Zhan_Web_Servlet/filedownload?filename=a.zip">a.zip</a> 15 </body> 16 </html>
Servlet配置文件部分:
1 <servlet> 2 <description></description> 3 <display-name>FileDownloadServlet</display-name> 4 <servlet-name>FileDownloadServlet</servlet-name> 5 <servlet-class>demo.FileDownloadServlet</servlet-class> 6 </servlet> 7 <servlet-mapping> 8 <servlet-name>FileDownloadServlet</servlet-name> 9 <url-pattern>/filedownload</url-pattern> 10 </servlet-mapping>
demo包下面的FileDownloadServlet如下:
1 package demo; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.ServletOutputStream; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 public class FileDownloadServlet extends HttpServlet { 14 15 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 16 //获取要下载文件的名称 17 String fileName = request.getParameter("filename"); 18 19 //客户端通过文件的MIME区分下载的文件的类型,所以在服务器端设置文件的MIME类型 20 response.setContentType(this.getServletContext().getMimeType(fileName)); 21 //告诉客户端不要直接解析该文件,而是以附件的形式打开(下载) 22 response.setHeader("Content-Disposition", "attachment;filename=" + fileName); 23 24 //获取要下载文件的绝对路径 25 String realPath = this.getServletContext().getRealPath("download/" + fileName); 26 27 ServletOutputStream out = response.getOutputStream(); 28 InputStream in = new FileInputStream(realPath); 29 int len = 0; 30 byte[] buffer = new byte[1024]; 31 while((len = in.read(buffer)) != -1) { 32 out.write(buffer, 0, len); 33 } 34 in.close(); 35 out.close(); 36 } 37 38 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 39 doGet(request, response); 40 } 41 }
启动服务器,访问download.html,界面如下:
点击要下载的文件链接即可下载。
以上是关于Servlet 下载文件的主要内容,如果未能解决你的问题,请参考以下文章
使用超链接和后台Servlet实现文件上传和下载(附图和代码)