1. 程式人生 > >java實現多個檔案打包下載

java實現多個檔案打包下載

最近需要做一個多檔案打包zip下載的需求,能力不足,完全無處下手,百度大法到了這個方法,轉載至此,以備後用。

親測有效,直接把方法貼上至專案就可以。

List<File> 需要先做一些操作,可以另寫一個方法,判斷手中的路徑是否為空,然後直接呼叫downLoadFiles這個方法就可以了。


public static HttpServletResponse downLoadFiles(List<File> files,HttpServletResponse response)throws Exception {

        try {
           //List<File> 作為引數傳進來,就是把多個檔案的路徑放到一個list裡面

            //建立一個臨時壓縮檔案

           //臨時檔案可以放在CDEF盤中,但不建議這麼做,因為需要先設定磁碟的訪問許可權,最好是放在伺服器上,方法最後有刪除臨時檔案的步驟

            String zipFilename =  "D:/tempFile.zip" ;
            File file = new File(zipFilename);
            if (!file.exists()){   
                file.createNewFile();   
            }
            response.reset();
            //response.getWriter()
            //建立檔案輸出流
            FileOutputStream fous = new FileOutputStream(file);   
           ZipOutputStream zipOut = new ZipOutputStream(fous);
           zipFile(files, zipOut);
            zipOut.close();
            fous.close();
           return downloadZip(file,response);
        }catch (Exception e) {
                e.printStackTrace();
            }
        return response ;
    }

  /**
     * 把接受的全部檔案打成壓縮包
     * @param List<File>;  
     * @param org.apache.tools.zip.ZipOutputStream  
     */
    public static void zipFile (List files,ZipOutputStream outputStream) {
        int size = files.size();
        for(int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }
    /**  
     * 根據輸入的檔案與輸出流對檔案進行打包
     * @param File
     * @param org.apache.tools.zip.ZipOutputStream
     */
    public static void zipFile(File inputFile,  ZipOutputStream ouputStream) {
        try {
            if(inputFile.exists()) {
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向壓縮檔案中輸出資料   
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 關閉建立的流物件   
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
        if(file.exists() == false){  
            System.out.println("待壓縮的檔案目錄:"+file+"不存在.");  
        }else{
            try {
            // 以流的形式下載檔案。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
    
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
    
            //如果輸出的是中文名的檔案,在此處就要用URLEncoder.encode方法進行處理
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(file.getName().getBytes("GB2312"), "ISO8859-1"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            } catch (IOException ex) {
            ex.printStackTrace();
            }finally{
                 try {
                        File f = new File(file.getPath());
                        f.delete();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }
        return response;
    }