2013-10-10 192 views
2

我一直在開發一個java web應用程序,我想添加一個下載功能。 我想下載位於「C:\ apache-tomcat-6.0.36 \ webapps \ xml \ XML.zip」中的zip文件。 我已經將文件轉換爲InputStream,但我仍然困惑如何從InputStream獲取輸入流數據?如何從輸入流文件獲取輸入流?

當我點擊下載按鈕,它會返回zip文件

這裏的0(零)字節是處理下載壓縮文件控制器:

@RequestMapping("download") 
public String Download(HttpServletResponse response) { 

    ZipInputStream zis = null; 

    try {   

     InputStream is = new FileInputStream("C:\\apache-tomcat-6.0.36\\webapps\\xml\\XML.zip"); 
     zis = new ZipInputStream(is); 

     response.setHeader("Content-Disposition", "inline;filename=\"" + "XML.zip" + "\""); 
     OutputStream out = response.getOutputStream(); 
     response.setContentType("application/zip"); 
     IOUtils.copy(zis.getInputStream, out); 
     out.flush(); 
     out.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    return null; 
} 

這條線是導致零字節拉鍊文件:

IOUtils.copy(**zis.getInputStream**, out); 
+0

您的文件路徑未被引用(「C:\\ apache」)。這是在你的代碼中嗎? – SJuan76

+2

我很疑惑......爲什麼包含下載按鈕的圖片很重要? – ppeterka

+2

另外,如果你想得到整個ZIP文件的下載,你不必使用ZipInputStream ...這是訪問_the ZIP文件的內容...而不是'zis.getInputStream()'使用'是.getInputStream()',並刪除與ZipInputStream相關的代碼... – ppeterka

回答

2

如果你想獲得整個壓縮文件下載,你不必使用ZipInputStream ...這是訪問內容的ZIP文件的 ...

代替zis.getInputStream()使用is.getInputStream(),並刪除相關ZipInputStream代碼:

@RequestMapping("download") 
public String Download(HttpServletResponse response) { 

    //ZipInputStream zis = null; no need for this 

    try {   

    InputStream is = new FileInputStream("C:\\apache-tomcat-6.0.36\\webapps\\xml\\XML.zip"); 
    //zis = new ZipInputStream(is); //no need for this 

    response.setHeader("Content-Disposition", "inline;filename=\"" + "XML.zip" + "\""); 
    OutputStream out = response.getOutputStream(); 
    response.setContentType("application/zip"); 
    IOUtils.copy(is, out); //no zis here, and "is" is already an InputStream instance 
    out.flush(); 
    out.close(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 

    return null; 
} 

另外,我會修改.close()調用:它們幾乎總是最適合finally塊,以確保正常關閉。 (或使用試用資源塊)。