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

标签 jsf primefaces

这个问题在这里已经有了答案:





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/

相关文章:

JSF 2 : selection grouping with SelectItemGroup + POJO

javascript - 无法访问jsf组件中的javascript文件

java - 如何遍历屏幕上显示的所有组件

jsf - h :button and h:commandButton 之间的差异

JSF 2.3 具有泛型的自定义转换器

jsf - PrimeFaces Dialog + appendToBody=true 不起作用

css - 更改 Accordion 面板选项卡的颜色

java - 是否可以从 JSFManagedBean 中的 UiComponent 对象生成 Facelets 代码

google-chrome - primefaces 图表中的文本失真

jsf - Primefaces 日历设置区域设置