【问题标题】:Download .pdf in jsp page在 jsp 页面中下载 .pdf
【发布时间】:2015-11-18 20:51:50
【问题描述】:

我正在使用 jsp 和 servlet 编写一个 Web 应用程序。我想为 jsp 页面中的每张图片有一个不同的 pdf 文件。我的事情是我应该将 id 发送到服务器并在那里让那个 id 得到正确的 pdf。你能给我一些帮助吗?

protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet rs = null;
    try {
        connection = WebDBConnectionsPool.getConnection();
    } catch (Exception e1) {
        e1.printStackTrace();
    }

    try {

        String filepath = null;
        String bookId = request.getParameter("id");

        statement = connection.prepareStatement("SELECT filepath FROM books WHERE bookid=?");
        statement.setString(1, bookId);
        rs = statement.executeQuery();
        while (rs.next()) {

            filepath = rs.getString("filepath");
        }
            String path = filepath;
            File downloadFile = new File(path);
            FileInputStream inStream = new FileInputStream(downloadFile);

            // if you want to use a relative path to context root:
            String relativePath = getServletContext().getRealPath("");
            System.out.println("relativePath = " + relativePath);

           File pdfFolder =
                         new File(request.getSession().getServletContext().getRealPath("/pdf"));

           // obtains ServletContext
           ServletContext context = getServletContext();

           // gets MIME type of the file
           String mimeType = context.getMimeType(filePath);
           if (mimeType == null) {        
               // set to binary type if MIME mapping not found
               mimeType = "application/octet-stream";
           }
    //        System.out.println("MIME type: " + mimeType);

           // modifies response
           response.setContentType(mimeType);
           response.setContentLength((int) downloadFile.length());

           // forces download
           String headerKey = "Content-Disposition";
           String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
           response.setHeader(headerKey, headerValue);

           // obtains response's output stream
           OutputStream outStream = response.getOutputStream();

           byte[] buffer = new byte[4096];
           int bytesRead = -1;

           while ((bytesRead = inStream.read(buffer)) != -1) {
               outStream.write(buffer, 0, bytesRead);
           }

           inStream.close();
           outStream.close();     
       }






   <% 
         for (int i = 0; i < data.getBooks().size(); i++) {
               Book book = (Book)data.getBooks().get(i);
         %>
       <article class="ebook cf">
          <img src="<%=book.getBookImage()%>">
          <div class="ebooks-description">
             <h4><%=book.getBookName()%></h4>
             <form>
                <input type="button" value="download" onclick="downloadFileAsynch('../DownloadFileServlet?id=<%=book.getBookId() %>');"/>
             </form>
          </div>
        </article> 
         <% } %>




 <script>
        function downloadFileAsynch(url){
        var elemIF = document.createElement("iframe");
        elemIF.name="file";
        elemIF.src = url;
        elemIF.style.display = "none";
        document.body.appendChild(elemIF);
        }
     </script>

【问题讨论】:

  • 还有什么问题?
  • 我的路径有些问题。
  • java.io.FileNotFoundException: ./pdf/ebook01.jpg(没有这样的文件或目录)在 java.io.FileInputStream.open(本机方法)在 java.io.FileInputStream. (FileInputStream.java:146) 在 com.sthhh.web.beautyclub.DownloadFileServlet.doGet(DownloadFileServlet.java:48)

标签: java jsp servlets


【解决方案1】:

在控制台 java 程序中,如果您要读取的文件在您正在运行的代码所在的目录下,您可以像“./pdf/ebook01.jpg”一样读取它,但在 servlet 中它不会那样工作。在 servlet 中,您的“./”需要替换为 context.getRealPath("/")

context.getRealPath("/") + "/pdf/ebook01.jpg"

好的,所以再次查看您的代码,您显然知道(?)只是您的代码非常混乱且不一致,因此您将路径保存到变量中(或尝试保存),然后从未实际使用过该变量。

你有String relativePath = getServletContext().getRealPath(""); 和稍后的request.getSession().getServletContext().getRealPath("/pdf") 和后来的ServletContext context = getServletContext(); 一些一致性和组织怎么样?

ServletContext context = getServletContext();
String relativePath = context.getRealPath("/");

然后确保无论您在何处阅读您实际使用的文件relativePath...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2015-07-08
    • 1970-01-01
    • 2019-06-28
    相关资源
    最近更新 更多