Java實現多檔案邊壓縮邊下載

指尖飄落的程式發表於2018-06-13

思路:一邊壓縮一邊下載,將多個檔案逐一寫入到壓縮檔案中

@ResponseBody
@GetMapping("/download")
public void downloadFiles(HttpServletRequest request, HttpServletResponse response){
    /*
    *  test
    * */
    List<String> list = new ArrayList<>();
    list.add("F:\\1\\test\\2\\1.exe");
    list.add("F:\\1\\test\\2\\2.exe");
    list.add("F:\\1\\test\\2\\3.exe");

    //響應頭的設定
    response.reset();
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/octet-stream;charset=utf-8");// 設定response內容的型別

    //設定壓縮包的名字
    //解決不同瀏覽器壓縮包名字含有中文時亂碼的問題
    String downloadName = "test.zip";
    String agent = request.getHeader("USER-AGENT");
    ZipOutputStream zipos = null;
    //迴圈將檔案寫入壓縮流
    DataOutputStream os = null;
    try {
        if (agent.contains("MSIE")||agent.contains("Trident")) {
            downloadName = java.net.URLEncoder.encode(downloadName, "UTF-8");
        } else {
            downloadName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;fileName=\"" + downloadName + "\"");

        //設定壓縮流:直接寫入response,實現邊壓縮邊下載
        zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
        zipos.setMethod(ZipOutputStream.DEFLATED); //設定壓縮方法

        for(int i = 0; i < list.size(); i++ ){

            InputStream is = null;
            try{
                File file = new File(list.get(i));
                if(file.exists()){
                    //新增ZipEntry,並ZipEntry中寫入檔案流
                    //這裡,加上i是防止要下載的檔案有重名的導致下載失敗
                    zipos.putNextEntry(new ZipEntry(i + "_" + file.getName()));
                    os = new DataOutputStream(zipos);
                    is = new FileInputStream(file);
                    byte[] b = new byte[1024];
                    int length = 0;
                    while((length = is.read(b))!= -1){
                        os.write(b, 0, length);
                    }
                }
            } finally {
                if(null != is){
                    is.close();
                }
                zipos.closeEntry();
            }

        }
        if(null != os){
            os.flush();
        }


    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        //關閉流
        try {
            if(null != os){
                os.close();
            }
            if(null != zipos){
                zipos.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


原始碼: https://github.com/gcWpengfei/spring-cloud-rsa-aes-demo/blob/master/aes-rsa-download/src/main/java/com/wpf/controller/DownloadController.java

相關文章