从服务器下载文件并以zip格式压缩

时间:2016-07-20 00:56:35

标签: jsf primefaces

我试图实现下载所有功能,我的要求是文件应该在.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提示“无法打开文件作为存档”#39;错误

1 个答案:

答案 0 :(得分:4)

更改

file = new DefaultStreamedContent(stream, "zip", "photos.zip"); 

file = new DefaultStreamedContent(stream, "application/zip", "photos.zip",  Charsets.UTF_8.name());

修好了