java 生成zip文件並瀏覽器導出


總結一下,關於Java下載zip文件並導出的方法,瀏覽器導出。

復制代碼
     String downloadName = "下載文件名稱.zip";
        downloadName = BrowserCharCodeUtils.browserCharCodeFun(request, downloadName);//下載文件名亂碼問題解決
        
        //將文件進行打包下載
        try {
            OutputStream out = response.getOutputStream();
            byte[] data = createZip("/fileStorage/download");//服務器存儲地址
            response.reset();
            response.setHeader("Content-Disposition","attachment;fileName="+downloadName);
            response.addHeader("Content-Length", ""+data.length);
            response.setContentType("application/octet-stream;charset=UTF-8");
            IOUtils.write(data, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
復制代碼

 

 

//獲取下載zip文件流

復制代碼
public byte[] createZip(String srcSource) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //將目標文件打包成zip導出
        File file = new File(srcSource); 
        a(zip,file,"");
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }
復制代碼

 

復制代碼
public void a(ZipOutputStream zip, File file, String dir) throws Exception {
            //如果當前的是文件夾,則進行進一步處理
            if (file.isDirectory()) {
                //得到文件列表信息
                File[] files = file.listFiles();
                //將文件夾添加到下一級打包目錄
                zip.putNextEntry(new ZipEntry(dir + "/"));
                dir = dir.length() == 0 ? "" : dir + "/";
                //循環將文件夾中的文件打包
                for (int i = 0; i < files.length; i++) {
                    a(zip, files[i], dir + files[i].getName());         //遞歸處理
                }
            } else {   //當前的是文件,打包處理
                //文件輸入流
               BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
               ZipEntry entry = new ZipEntry(dir);
               zip.putNextEntry(entry);
               zip.write(FileUtils.readFileToByteArray(file));
               IOUtils.closeQuietly(bis);
               zip.flush();
               zip.closeEntry();
            }
    }
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM