簡體   English   中英

從servlet Java下載zip

[英]Download a zip from a servlet Java

我不明白為什么這么難,每個人都有自己的實施......

所以在我的服務器中,我生成一個.zip文件,我希望用戶能夠在點擊時下載。

所以我設置了服務器成功接收的請求,現在,我正在努力將字節數組寫入輸出。

這是我的響應代碼:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("Downloading clusters.zip");

        /* Generate the directory on the server, then zip it. */
        clustersToFiles();
        zipClusters();
        /* Now the zip is saved on zipFullPath */

        System.out.println("Done generating the .zip");

        String parent_dir = System.getProperty("catalina.base");
        String filename = "clusters.zip";
        String zipFullPath = parent_dir + "/" + filename;

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
        OutputStream out = response.getOutputStream();

        FileInputStream fis = new FileInputStream(zipFullPath);
        int bytes;
        while ((bytes = fis.read()) != -1) {
            System.out.println(bytes);
            out.write(bytes);
        }
        fis.close();
        response.flushBuffer();

        System.out.println(".zip file downloaded at client successfully");
}

下載的文件是ZIP的事實是不相關的(內容類型除外),您只想下載二進制文件。

PrintWriter並不擅長這個,這個編寫器用於編寫文本輸出,以及您正在使用的write(int)方法:

寫一個字符

只需使用低級普通OutputStream ,其write(int)方法:

將指定的字節寫入此輸出流。

所以,去吧:

OutputStream out = response.getOutputStream();

您可以在此問題中找到更多方法: 實現簡單的文件下載servlet

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM