zoukankan      html  css  js  c++  java
  • 通过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("/")

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

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

    痛苦预示着超脱
  • 相关阅读:
    CSS选择器
    基础DOS命令
    超链接a标签
    vscode使用技巧
    pc端页面添加meta标签:X-UA-Compatible meta标签
    提问的智慧
    Zepto核心模块源代码分析
    远程调试工具weinre使用教程
    HTML标签marquee实现滚动效果
    git 学习教程
  • 原文地址:https://www.cnblogs.com/supperlhg/p/8080087.html
Copyright © 2011-2022 走看看