[英]Corrupted ZIP file from Resteasy download
問題是,從REST服務下載zip文件后,我有類似的東西:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Disposition: attachment; filename=Report_request_2681.zip
Content-Type: application/octet-stream
Content-Length: 1843
Date: Tue, 24 May 2016 15:24:39 GMT
PK etc etc... my real zip file bytes
生成的zip文件是正確的(嘗試直接從服務器復制它,大小為1843字節),故障在於下載方法(resteasy將HTTP頭添加到文件中,因此最終大小為1843字節+標題部分) 。 這是我的resteasy
實現(我刪除了沒有影響的部分):
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Path("/download/{fileName}")
Response getRequestedFile(
@Context HttpServletRequest httpRequest,
@PathParam("fileName") String fileName
);
//... bla bla bla method and authentication stuff
//Prepare a file object with file to return
File file = new File(myPath);
if (!file.exists()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
try {
return Response.ok(FileUtils.readFileToByteArray(file), MediaType.APPLICATION_OCTET_STREAM_TYPE).header("Content-Disposition", "attachment; filename=\"" + cleanFileName + "\"").build();
} catch (IOException ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
我正在使用resteasy 2.1.0 GA
(我無法升級它)。 readFileToByteArray
方法取自org.apache.commons.io.FileUtils
。 我已經嘗試將內容設置為text / plain或application / zip並將FileInputStream傳遞給Response,但問題仍然存在。 有小費嗎?
哦,我也試過通過REST方法下載一個簡單的文本文件...同樣的問題,在下載的文件的開頭,我有HTTP響應頭:
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Disposition: attachment; filename="Report_request_2681"
Content-Type: application/octet-stream
Content-Length: 16550
Date: Wed, 25 May 2016 07:03:20 GMT
...rest of my txt file
編輯:問題中的綜合評論信息。
沒有找到針對此問題的簡單解決方案,因為我已經創建了一個servlet來下載文件(從新URL,壓縮文件沒有損壞),所以我改變了我的resteasy
實現來進行重定向:
....
String redirectPath = StringUtils.substringBefore(httpRequest.getRequestURL().toString(), "restws") + "download?fileName=" + fileName + "&actionId=" + actionRequestId + "&check=" + encodedString;
return Response.seeOther(URI.create(redirectPath)).build();
其中check
參數是簡單編碼標記,包含用於simmetric安全性的時間戳。 它避免了servlet中的完整身份驗證/角色邏輯端口(如果在REST方法的不到3秒內沒有調用servlet URL,請求將返回400)。 不是一個優雅的解決方案,但至少現在文件不再被破壞。
PS順便說一句,就像一個注釋: WinRAR
將處理損壞的文件就好(也就是7zip
版本9.2), Windows Explorer
和7zip
的最后一個版本無法打開它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.