2014-06-25 27 views
1

我需要提供一個幫助用戶下載文件的寧靜服務。Java文件下載rest服務,byte []數組中的內容

我有文件的如下(以byte []數組,和文件名文件的內容)的細節。我看到很少有人使用File對象或FileOutputStream對象,他們可以爲attachment文件名等設置標題。我不知道如何將byte[]數組轉換爲File或可以在Response中設置的任何特定對象。我有下面的代碼,下載文件,但ID不會添加任何信息頭(請看看註釋代碼 - 如果可以修復以擺脫例外)

我不確定這是否正確的文件類型@Produces(MediaType.APPLICATION_OCTET_STREAM)可以是word文檔/ excell或PDF。

@GET 
    @Produces(MediaType.APPLICATION_OCTET_STREAM) 
    @Path("/download-file") 
    public byte[] download(@QueryParam("fileID") Long fileID) { 

     byte[] contents = getFileContents(fileID); 
     String file_name = getFileName(fileID); 
     return contents; 

     /* ResponseBuilder response = null; 
     try { 
      FileOutputStream out = new FileOutputStream(file_name); 
      out.write(contents); 
      response = Response.ok((Object) out); 
      response.header("content-type", "application/octet-stream"); 
      out.close(); 

     } catch (Exception e) { 
      e.printStackTrace(); 

     } 

     response.header("Content-Disposition","attachment; filename="+file_name); 
     return response.build();*/ 
    } 

如何返回byte []數組內容以及設置頭內容處置?

上面的代碼給了我下面的異常

A message body writer for Java class java.io.FileOutputStream, and Java type class java.io.FileOutputStream, and MIME media type application/octet-stream was not found. 
The registered message body writers compatible with the MIME media type are: 
application/octet-stream -> 
    com.sun.jersey.core.impl.provider.entity.ByteArrayProvider 
    com.sun.jersey.core.impl.provider.entity.FileProvider 
    com.sun.jersey.core.impl.provider.entity.InputStreamProvider 
    com.sun.jersey.core.impl.provider.entity.DataSourceProvider 
    com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider 
*/* -> 

同樣的註釋的代碼工作,如果我做跟隨它的變化

File file = new File(absolute_path_to_file); 
response = Response.ok((Object) file); 

似乎Response.ok可以接受File對象,但沒有任何其他對象,但正如我所提到的,我沒有絕對的路徑。我有文件contents作爲byte []數組。 注意:如果您想建議我將這些byte []數組寫入文件,然後從該文件創建File對象。 Akhhh! (這將是我的最後一個選擇)。我能否在不寫文件的情況下達到相同的目我已經看到一些Response.ok可以接受一些OutStream相關對象,但不知道如何將字節轉換爲Response支持的對象之一。

+0

你可能要考慮使用StreamingOutput,因爲你顯然使用JAX-RS。 –

回答

1

您應該將內容類型設置爲特定文件的MIME類型。否則,客戶端瀏覽器很難確定如何處理文件。

此外,您應該設置Content-Disposition標題,正如您在未評論的代碼中嘗試。

然而,你應該只返回原始字節數組沒有任何包裝它(雖然你可以使用Response包裝對象設置正確的頭)

相關問題