如何在Java中提供本地PDF文件的下载?

时间:2012-07-11 08:43:28

标签: java pdf download

我将JBoss作为应用程序服务器运行,并且在我的HD上的某处有一个PDF文件,当用户点击特定操作时会创建该文件。假设文件在这里:C:/PDF/doonot/10.07.2012/doonot.pdf。如何提供此文件作为下载?我已经为CSV文件做了,但我不知道如何用PDF做。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:1)

正如我在Is there a common way to download all types of files in jsp?

上写的那样

你可以使用这样的东西:

public HttpServletResponse getFile (HttpServletRequest request ,HttpServletResponse httpServletResponse, .......){
          HttpServletResponse response = httpServletResponse;
          InputStream in =/*HERE YOU READ YOUR FILE AS BinaryStream*/

          String filename = "";
          String agent = request.getHeader("USER-AGENT");
          if (agent != null && agent.indexOf("MSIE") != -1)
          {
            filename = URLEncoder.encode(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8");
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition","attachment;filename=" + filename);
          }
          else if ( agent != null && agent.indexOf("Mozilla") != -1)
          {
            response.setCharacterEncoding("UTF-8");
            filename = MimeUtility.encodeText(/*THIS IS THE FILENAME SHOWN TO THE USER*/, "UTF8", "B");
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
          }


          BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
          byte by[] = new byte[32768];
          int index = in.read(by, 0, 32768);
          while (index != -1) {
              out.write(by, 0, index);
              index = in.read(by, 0, 32768);
          }
          out.flush();

          return response;
}

<强>更新

不要忘记您可以使用InputStream:

// read local file into InputStream
InputStream inputStream = new FileInputStream("c:\\SOMEFILE.xml");

或者你可以像这样使用它

//read from database
Blob blob = rs.getBlob(1);
InputStream in = blob.getBinaryStream();

答案 1 :(得分:0)

您可以简单地编写一个读取pdf的servlet并将其写入响应输出流。

例如:http://www.java-forums.org/blogs/servlet/668-how-write-servlet-sends-file-user-download.html

答案 2 :(得分:0)

是古斯塔夫是对的。 Java不区分文件类型。文件是一个文件,如果你是为csv做的,它也适用于pdf。