總結一下,關於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(); } }