点击pdf/word等链接时时,直接打开而不是下载的方法

  1. <%@ page session="false" pageEncoding="UTF-8"%>   
  2. <%@page import="java.io.*"%>   
  3. <%   
  4.   response.setContentType("application/pdf");   
  5.   
  6.   out.clearBuffer(); // 如果使用JSP,需要加上这一句     
  7.   OutputStream os = response.getOutputStream(); // 页面输出流,jsp/servlet都可以     
  8.   response.addHeader("Content-Disposition"new String(("filename=pattern.pdf")   
  9.       .getBytes("GBK"), "ISO-8859-1")); // 针对中文文件名     
  10.   File f = new File(application.getRealPath(".")+"/pattern.pdf"); // 你的文件     
  11.   InputStream is = new FileInputStream(f); // 文件输入流     
  12.   byte[] bs = new byte[1024]; // 读取缓冲区     
  13.   int len;   
  14.   while ((len = is.read(bs)) != -1) { // 循环读取     
  15.     os.write(bs, 0, len); // 写入到输出流     
  16.   }   
  17.   is.close(); // 关闭     
  18.   os.close(); // 关闭   
  19. %>  
<%@ page session="false" pageEncoding="UTF-8"%>
<%@page import="java.io.*"%>
<%
  response.setContentType("application/pdf");

  out.clearBuffer(); // 如果使用JSP,需要加上这一句  
  OutputStream os = response.getOutputStream(); // 页面输出流,jsp/servlet都可以  
  response.addHeader("Content-Disposition", new String(("filename=pattern.pdf")
      .getBytes("GBK"), "ISO-8859-1")); // 针对中文文件名  
  File f = new File(application.getRealPath(".")+"/pattern.pdf"); // 你的文件  
  InputStream is = new FileInputStream(f); // 文件输入流  
  byte[] bs = new byte[1024]; // 读取缓冲区  
  int len;
  while ((len = is.read(bs)) != -1) { // 循环读取  
    os.write(bs, 0, len); // 写入到输出流  
  }
  is.close(); // 关闭  
  os.close(); // 关闭
%>



请注意这一句

  1. response.addHeader("Content-Disposition"new String(("filename=pattern.pdf")   
  2.       .getBytes("GBK"), "ISO-8859-1")); // 针对中文文件名    
response.addHeader("Content-Disposition", new String(("filename=pattern.pdf")
      .getBytes("GBK"), "ISO-8859-1")); // 针对中文文件名  
如果要下载的话,就改成
  1. response.addHeader("Content-Disposition"new String(("attachment; filename=pattern.pdf")   
  2.       .getBytes("GBK"), "ISO-8859-1")); // 针对中文文件名    
response.addHeader("Content-Disposition", new String(("attachment; filename=pattern.pdf")
      .getBytes("GBK"), "ISO-8859-1")); // 针对中文文件名  






这个东西在http协议里面有规定。

顺便说一句,filename是你下载或者另存为时的文件名,必须用iso-8859-1的编码才可以。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值