2017-02-28 90 views
0

我从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); 
} 
} 
+0

您可能会过早关闭流,或者根本不关闭流。你可以添加源代码吗? – bekce

+0

我加了代码,但是,正如我所说的那样,它在1.4.3的弹簧启动中起作用。 – BadChanneler

回答

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

我认为完成,正在做。非常感谢 ! – BadChanneler

+0

谢谢你的接受,玩得开心:) – bekce