通过URL传递PDF名称参数显示PDF

 1 <%@ page language="java" import="java.util.*,java.io.*"
 2 pageEncoding="UTF-8"%>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme() + "://"
 6     + request.getServerName() + ":" + request.getServerPort()
 7     + path + "/";
 8 %>
 9 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
10 <html>
11 <head>
12 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
13 <title>PDF文件显示</title>
14 </head>
15 <%
16     out.clear();
17    out = pageContext.pushBody();
18    response.setContentType("application/pdf"); 19 20 request.setCharacterEncoding("UTF-8");// 设置接收的字符集 21 22 try { 23 24 //这块由于中文参数的编码问题导致参数传递出现bug 如果解决这个问题则迎刃而解 25 String name = new String(request.getParameter("name").getBytes("iso-8859-1"),"UTF-8");//但是这个对于有特殊字符的文件名称而言并不可靠 26 String strPdfPath = new String("C:/Users/1101399/Desktop/PDF/" + name); 27 //判断该路径下的文件是否存在 28 File file = new File(strPdfPath); 29 if (file.exists()) { 30 DataOutputStream temps = new DataOutputStream(response.getOutputStream()); 31 DataInputStream in = new DataInputStream(new FileInputStream(strPdfPath)); 32 33 byte[] b = new byte[2048]; 34 while ((in.read(b)) != -1) { 35  temps.write(b); 36  temps.flush(); 37  } 38 39 in.close(); 40  temps.close(); 41 } else { 42 out.print(strPdfPath + " 文件不存在!"); 43  } 44 45 } catch (Exception e) { 46  out.println(e.getMessage()); 47  } 48 %> 49 <body> 50 <br> 51 </body> 52 <script type="text/javascript"> 53 </script> 54 </html>

 

我们在调用这个jsp界面时只需要传入对应的文件名称参数即可实现显示对应的PDF文件。

 

 

又及:

如果我们想要确切的使用web项目发布之后服务器的文件则将PDF的文件地址换位如下

1 String strPdfPath = new String(request.getSession().getServletContext().getRealPath("/") + "/WEB-INF/jsp/wareHouse/" + name);
我们通过
1 request.getSession().getServletContext().getRealPath("/")

来确定服务器的根文件目录

这块也换成任何服务器可以访问到的文件地址,这样我们可以将文件存储于项目文件分离便于管理

转载于:https://www.cnblogs.com/supperlhg/p/8080087.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值