我從spring啓動1.4.3.RELEASE切換到1.5.1.RELEASE。我有一個HttpServletResponse,我可以通過這個HttpServletResponse編寫可以通過休息端點下載的存檔內容。該文件被下載,但我無法用zip解壓縮器打開它,而使用spring boot 1.4.3時則不是這樣。升級到Spring啓動後無法打開zip存檔1.5.1
的響應頭看起來像這樣
X-Frame-Options:DENY
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
X-Content-Type-Options:nosniff
Content-Disposition:attachment; filename="myfile.zip"
Connection:close
Pragma:no-cache
Expires:0
Content-Transfer-Encoding:binary
X-XSS-Protection:1; mode=block
Content-Length:1054691
Date:Tue, 28 Feb 2017 05:39:32 GMT
Content-Type:application/zip
那些有責任與文件寫入到響應的方法:
public void writeZipToResponse(HttpServletResponse response) throws IOException {
Optional<MyObject> myObject= findMyObject();
if (myObject.isPresent()) {
response.addHeader("Content-type", AdditionalMediaTypes.APPLICATION_ZIP);
response.addHeader("Content-Transfer-Encoding", "binary");
response.addHeader("Content-Disposition", "attachment; filename=\"" + myObject.get().getName() + ".zip\"");
response.setStatus(HttpStatus.OK.value());
int lengthOfFile = writeObjectAsArchive(myObject.get(), response.getOutputStream());
response.addHeader("Content-Length", String.valueOf(lengthOfFile));
}
else {
response.setStatus(HttpStatus.NOT_FOUND.value());
}
}
這:
int writeObjectAsArchive(Collection<Dummy> dummies, OutputStream out) {
try {
ZipOutputStream zipArchive = new ZipOutputStream(out);
int length = 0;
for (Dummy dummy: dummies) {
ZipEntry entry = new ZipEntry(dummy.getFileName());
zipArchive.putNextEntry(entry);
byte[] fileAsByteArray = dummy.getFileAsByteArray();
zipArchive.write(fileAsByteArray);
zipArchive.closeEntry();
length += fileAsByteArray.length;
}
zipArchive.finish();
return length;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
您可能會過早關閉流,或者根本不關閉流。你可以添加源代碼嗎? – bekce
我加了代碼,但是,正如我所說的那樣,它在1.4.3的彈簧啓動中起作用。 – BadChanneler