我需要提供一個幫助用戶下載文件的寧靜服務。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
可以接受一些Out
或Stream
相關對象,但不知道如何將字節轉換爲Response
支持的對象之一。
你可能要考慮使用StreamingOutput,因爲你顯然使用JAX-RS。 –