Spring boot 升级到Spring boot 1.5.1后无法打开zip存档
我从spring boot 1.4.3.RELEASE切换到1.5.1.RELEASE。我有一个HttpServletResponse,我将向其写入存档的内容,该内容可通过rest端点下载。该文件已下载,但我无法再使用zip unarchiver打开它,这与使用SpringBoot1.4.3时的情况不同 响应头如下所示Spring boot 升级到Spring boot 1.5.1后无法打开zip存档,spring-boot,Spring Boot,我从spring boot 1.4.3.RELEASE切换到1.5.1.RELEASE。我有一个HttpServletResponse,我将向其写入存档的内容,该内容可通过rest端点下载。该文件已下载,但我无法再使用zip unarchiver打开它,这与使用SpringBoot1.4.3时的情况不同 响应头如下所示 X-Frame-Options:DENY Cache-Control:no-cache, no-store, max-age=0, must-revalidate X-Conte
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);
}
}
必须关闭输出流
int writeObjectAsArchive(Collection<Dummy> dummies, OutputStream out) {
try {
ZipOutputStream zipArchive = new ZipOutputStream(out);
...
zipArchive.finish();
zipArchive.close();
return length;
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
您可能过早地关闭流,或者根本不关闭它。你能添加源代码吗?我添加了代码,虽然,正如我在spring boot 1.4.3中所说的,这是有效的。我认为finish正在完成它。谢谢!