Content-Disposition属性有两种类型
- inline :将文件内容直接显示在页面
- attachment:弹出对话框让用户下载
弹出对话框下载文件
resp.setHeader("Content-Disposition", "attachment; filename="+fileName);
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 6 id="WebApp_ID" version="3.0"> 7 <display-name>DownloadDemo</display-name> 8 <welcome-file-list> 9 <welcome-file>index.jsp</welcome-file> 10 </welcome-file-list> 11 12 <servlet> 13 <servlet-name>download</servlet-name> 14 <servlet-class>com.qf.servlet.DownloadServlet2</servlet-class> 15 </servlet> 16 <servlet-mapping> 17 <servlet-name>download</servlet-name> 18 <url-pattern>/download</url-pattern> 19 </servlet-mapping> 20 </web-app>
servlet类
1 public class DownloadServlet2 extends HttpServlet { 2 3 @Override 4 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 5 //获取文件在tomcat下的路径 6 String path = getServletContext().getRealPath("download/bb.txt"); 7 8 //让浏览器收到这份资源的时候, 以下载的方式提醒用户,而不是直接展示 9 resp.setHeader("Content-Disposition", "attachment; filename=bb.txt"); 10 11 //转化成输入流 12 InputStream is = new FileInputStream(path); 13 OutputStream os = resp.getOutputStream(); 14 15 int len = 0; 16 byte[] bts = new byte[1024]; 17 while ((len = is.read(bts)) != -1) { 18 os.write(bts, 0, len); 19 } 20 os.close(); 21 is.close(); 22 } 23 24 @Override 25 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 26 doGet(req, resp); 27 } 28 }
url:http://localhost:8080/DownloadDemo/download
直接在浏览器页面打开文件
resp.setHeader("Content-Disposition", "inline; filename="+fileName);
修改servlet类
1 public class DownloadServlet2 extends HttpServlet { 2 3 @Override 4 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 5 //获取文件在tomcat下的路径 6 String path = getServletContext().getRealPath("download/bb.txt"); 7 8 //让浏览器收到这份资源的时候, 以下载的方式提醒用户,而不是直接展示 9 resp.setHeader("Content-Disposition", "inline; filename=bb.txt"); 10 11 //转化成输入流 12 InputStream is = new FileInputStream(path); 13 OutputStream os = resp.getOutputStream(); 14 15 int len = 0; 16 byte[] bts = new byte[1024]; 17 while ((len = is.read(bts)) != -1) { 18 os.write(bts, 0, len); 19 } 20 os.close(); 21 is.close(); 22 } 23 24 @Override 25 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 26 doGet(req, resp); 27 } 28 29 }