升级到Spring boot 1.5.1后无法打开zip存档

时间:2017-02-28 05:49:22

标签: spring-boot

我从spring boot 1.4.3.RELEASE切换到1.5.1.RELEASE。我有一个HttpServletResponse,我写了存档的内容,可以通过rest-endpoint下载。该文件已下载,但我无法使用zip unarchiver打开它,这在使用spring boot 1.4.3时并非如此。

响应标头看起来像这样

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);
}
 }

1 个答案:

答案 0 :(得分:1)

您必须关闭输出流。

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);
  }
}