2012-07-11 321 views
0

我將JBoss作爲應用程序服務器運行,並且我的HD上有一個PDF文件,當用戶單擊某個特定操作時會創建該文件。假設文件在這裏:C:/PDF/doonot/10.07.2012/doonot.pdf。我怎樣才能提供這個文件作爲下載?我已經做了一個CSV文件,但我不知道如何使用PDF。如何提供Java下載本地PDF文件?

任何幫助,非常感謝。

+3

你是如何做CSV文件? – 2012-07-11 08:44:45

+0

您是否使用某種Web應用程序提供用於下載的文件,或者您是否像使用ftp服務器一樣使用JBoss? – MaVRoSCy 2012-07-11 09:14:05

+0

不,該文件只存儲在服務器上。 – doonot 2012-07-11 11:19:36

回答

0

正如我在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; 
} 

UPDATE:

不要忘記,你可以使用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(); 
+0

你能解釋這是如何工作的:「你在這裏讀取你的文件作爲BinaryStream」? – doonot 2012-07-11 11:19:05

+0

@dooonot我更新了我的答案 – MaVRoSCy 2012-07-11 11:28:04

+0

Thx。但它不是BinaryStream,是嗎? – doonot 2012-07-11 11:34:07

0

您可以簡單地編寫一個讀取pdf的servlet並將其寫入響應輸出流。

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

+0

良好的輸入,會嘗試這一個! Thx – doonot 2012-07-11 08:51:13

+0

「打開此文檔時出錯,文件已損壞,無法修復」... – doonot 2012-07-11 11:15:04

+0

您可能會在文件的開頭或結尾處添加不需要的數據,或者不會刷新,或者其他任何內容。試着用你的servlet下載一個簡單的文本文件來看看發生了什麼。 – Anthony 2012-07-12 07:38:28

0

是古斯塔夫是正確的。 Java不區分文件類型。一個文件是一個文件,如果你爲csv做過,它也應該用於pdf。

+0

不,它不。它說文件已損壞,無法修復。 – doonot 2012-07-11 11:16:10