在jsp页面下载.pdf

时间:2015-11-18 20:51:50

标签: java jsp servlets

我正在用jsp和servlet编写一个Web应用程序。我想为jsp页面中的每张图片提供不同的pdf文件。我应该将id发送给发送者并在那里获得正确的pdf.Can你能给我一些帮助。

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>

1 个答案:

答案 0 :(得分:0)

在控制台java程序中,如果您要读取的文件位于目录下,作为您运行的代码,您可以通过&#34; ./ pdf / ebook01.jpg&#34;但是在servlet中,它不会那样工作。在servlet中,你的&#34; ./"需要替换为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 ...