2013-08-26 40 views
0

我有一個文件夾,我試圖壓縮它,而不是按鈕單擊事件,它應該下載到用戶的機器上。我能夠正確生成zip文件。我已經編寫了代碼來下載它,但在它從服務器上下載到用戶的機器之後。它顯示無法打開zip文件,因爲它是無效的。無法正確地從服務器上下載創建的壓縮文件

這是如何造成的,我該如何解決?這是執行下載功能的代碼。

public String getAsZip() {        
     try { 
     FacesContext ctx = FacesContext.getCurrentInstance(); 
     ExternalContext etx = ctx.getExternalContext(); 
     HttpServletResponse response = (HttpServletResponse) etx 
       .getResponse(); 
     ServletOutputStream zipFileOutputStream = response 
       .getOutputStream(); 
     response.setContentType("application/octet-stream"); 
     response.setHeader(
       "Content-Disposition", 
       "attachment; filename=" + downloadLink.substring(downloadLink.lastIndexOf("\\") + 1,downloadLink.length())); 
     response.setHeader("Cache-Control", "no-cache"); 

     File zipFile = new File(downloadLink); 
     FileInputStream stream = new FileInputStream(zipFile); 
     response.setContentLength(stream.available()); 

     int length = 0; 
     byte[] bbuf = new byte[response.getBufferSize()]; 
     BufferedInputStream in = new BufferedInputStream(stream); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

     while ((length = in.read(bbuf)) > 0) { 
      baos.write(bbuf, 0, length); 
     } 

     zipFileOutputStream.write(baos.toByteArray()); 
     zipFileOutputStream.flush(); 
     zipFileOutputStream.close(); 
     response.flushBuffer(); 
     in.close(); 
     stream.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return "successZip"; 
} 

回答

1

JSF 2.0 RenderResponse and ResponseComplete

的問題是,你不叫的FacesContext#responseComplete()方法。這就是爲什麼在附加下載並將其附加到響應之後,JSF仍會呈現視圖。這將導致zip文件被破壞。

+0

非常感謝沒有人。問題已解決 –

相關問題