简体   繁体   English

在jsp页面中下载.pdf

[英]Download .pdf in jsp page

I'm writing a web app with jsp and servlets. 我正在用jsp和servlet编写Web应用程序。 I want to have a different pdf file for each picture in jsp page. 我想在jsp页面中为每张图片使用不同的pdf文件。 I thing that I should send id to the servet and there for that id to get right pdf.Can you give me some help with that. 我应该将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>

In a console java program, if the file you want to read is under the directory as the code you are running, you can read it by like "./pdf/ebook01.jpg" but in a servlet it doesn't work that way. 在控制台Java程序中,如果要读取的文件位于您正在运行的代码所在的目录下,则可以通过“ ./pdf/ebook01.jpg”进行读取,但是在servlet中,这种方式不起作用。 In a servlet, your "./" will need to be replaced with context.getRealPath("/") : 在servlet中,您的“ ./”将需要替换为context.getRealPath("/")

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

Ok, so looking at your code again, you apparently know that(?) just your code is ridiculously messy and inconsistent so you saved the path into a variable (or tried to) and then never actually used the variable. 好的,所以再次查看您的代码,您显然知道(?)只是您的代码是混乱且不一致的,因此您将路径保存到变量中(或试图保存),然后从未实际使用过该变量。

You have String relativePath = getServletContext().getRealPath(""); 您有String relativePath = getServletContext().getRealPath(""); and a little later request.getSession().getServletContext().getRealPath("/pdf") and later ServletContext context = getServletContext(); request.getSession().getServletContext().getRealPath("/pdf")一会儿request.getSession().getServletContext().getRealPath("/pdf")和后来的ServletContext context = getServletContext(); How about some consistency and organization? 如何保持一致性和组织性?

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

And then make sure wherever you are reading the file you actually use relativePath ... 然后确保无论您在何处读取文件,都可以实际使用relativePath ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM