这个问题在这里已经有了答案:
Why do I have to close the ZipOutputStream in a certain way in this situation?
(2 个回答)
5年前关闭。
我正在尝试实现下载所有功能,我的要求是文件应以 .zip 格式压缩,这是 UI
<p:toolbar>
<f:facet name="right">
<p:commandButton value="Download all photos" ajax="false" actionListener="#{ManageActivities.getAllParticipantPhoto}" onclick="PrimeFaces.monitorDownload(start, stop);" icon="ui-icon-image">
<p:fileDownload value="#{ManageActivities.file}" />
</p:commandButton>
</f:facet></p:toolbar>
这是托管bean代码
private StreamedContent file;
public void getAllParticipantPhoto() {
ByteArrayInputStream bis = new ByteArrayInputStream(zipBytes());
InputStream stream = bis;
file = new DefaultStreamedContent(stream, "zip", "photos.zip");
}
private byte[] zipBytes () {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
try{
for(Participants p : partcpnts){
if(p.getPhoto() != null){
ZipEntry entry = new ZipEntry(p.getFirstName()+".jpg");
zos.putNextEntry(entry);
zos.write(p.getPhoto());
}
}
}catch(Exception e){
e.printStackTrace();
}
return baos.toByteArray();
}
我可以成功以 ZIP 格式下载文件,但无法解压缩,Windows 提示“无法将文件作为存档打开”错误
最佳答案
改变
file = new DefaultStreamedContent(stream, "zip", "photos.zip");
到
file = new DefaultStreamedContent(stream, "application/zip", "photos.zip", Charsets.UTF_8.name());
修复
关于jsf - 从服务器下载文件并以zip格式压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38470714/