java檔案下載程式碼例項(單檔案下載和多檔案打包下載)
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了java檔案下載程式碼例項(單檔案下載和多檔案打包下載),文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
最近專案有需要寫檔案下載相關程式碼,這邊提交記錄下相關程式碼模組,寫的不太好,後期再優化相關程式碼,有好的建議,可留言,謝謝。
1)單檔案下載
public String oneFileDownload(HttpServletRequest request,HttpServletResponse response){ //針對需求需要與需求溝通下載檔案傳遞引數 //目前demo檔名是檔案的hashCode值+字尾名的方式命名,可以預設該hashCode值為檔案唯一id String fileName = request.getParameter("fileName"); if(StringUtils.isBlank(fileName)){ return "檔名為空"; } String filePath = request.getSession().getServletContext().getRealPath("/convert")+File.separator+fileName;//目前檔案預設在該資料夾下,後續變動需修改 File downloadFile = new File(filePath); if(downloadFile.exists()){ OutputStream out = null; FileInputStream fis = null; BufferedInputStream bis = null; try { if(downloadFile.isDirectory()){ return "路徑錯誤僅指向資料夾"; } out = response.getOutputStream();// 建立頁面返回方式為輸出流,彈出下載框 fis = new FileInputStream(downloadFile); bis = new BufferedInputStream(fis); response.setContentType("application/pdf; charset=UTF-8");//設定編碼字元 response.setHeader("Content-disposition","attachment;filename=" + fileName); byte[] bt = new byte[2048]; int size = 0; while((size=bis.read(bt)) != -1){ out.write(bt,size); } } catch (Exception e) { e.printStackTrace(); }finally { try { //關閉流 out.flush(); if(out != null){ out.close(); } if(bis != null){ bis.close(); } if(fis != null){ fis.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return "下載成功"; }else{ return "檔案不存在!"; } }
2)多檔案打包下載
a)下載指定資料夾下的檔案,如果巢狀資料夾也支援(但檔名需要唯一)
public String zipDownload(HttpServletRequest request,HttpServletResponse response) throws IOException{ String sourceFilePath = request.getSession().getServletContext().getRealPath("/convert");//檔案路徑 String destinFilePath = request.getSession().getServletContext().getRealPath("/fileZip"); String fileName = FileUtil.zipFiles(sourceFilePath,destinFilePath); File file = new File(destinFilePath+File.separator+fileName); response.setHeader("Content-disposition","attachment;filename=" + fileName); if(file.exists()){ FileInputStream fis = null; BufferedInputStream bis = null; OutputStream out = response.getOutputStream(); try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); byte[] bufs = new byte[1024 * 10]; int read = 0; while ((read = bis.read(bufs,1024 * 10)) != -1) { out.write(bufs,read); } } catch (FileNotFoundException e) { e.printStackTrace(); }finally { if(bis != null){ bis.close(); } if(out!=null){ out.close(); } File zipFile = new File(destinFilePath+File.separator+fileName); if(zipFile.exists()){ zipFile.delete(); } } }else{ return "檔案壓縮失敗"; } return "下載成功"; }
b)下載指定資料夾下的所有檔案,支援樹型結構
public String zipDownloadRelativePath(HttpServletRequest request,HttpServletResponse response) { String msg ="";//下載提示資訊 String root = request.getSession().getServletContext().getRealPath("/convert");//檔案路徑 Vector<File> fileVector = new Vector<File>();//定義容器裝載檔案 File file = new File(root); File [] subFile = file.listFiles(); //判斷檔案性質並取檔案 for(int i = 0; i<subFile.length; i++){ if(!subFile[i].isDirectory()){//不是資料夾並且不為空 fileVector.add(subFile[i]);//裝載檔案 }else{//是資料夾,再次遞迴遍歷資料夾裡面的檔案 File [] files = subFile[i].listFiles(); Vector v = FileUtil.getPathAllFiles(subFile[i],new Vector<File>()); fileVector.addAll(v);//把迭代的檔案裝到容器中 } } //設定檔案下載名稱 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = dateFormat.format(new Date())+".zip"; response.setHeader("Content-disposition","attachment;filename=" + fileName);//如果有中文需要轉碼 //定義相關流 //用於瀏覽器下載響應 OutputStream out = null; //用於讀壓縮好的檔案 BufferedInputStream bis = null;//用快取效能會好一些 //用於壓縮檔案 ZipOutputStream zos = null; //建立一個空的zip檔案 String zipBasePath = request.getSession().getServletContext().getRealPath("/fileZip"); String zipFilePath = zipBasePath+File.separator+fileName; File zipFile = new File(zipFilePath); try { if(!zipFile.exists()){//不存在建立一個新的 zipFile.createNewFile(); } out = response.getOutputStream(); //建立檔案輸出流 zos = new ZipOutputStream(new FileOutputStream(zipFile)); //迴圈檔案,一個一個按順序壓縮 for(int i = 0;i< fileVector.size();i++){ System.out.println(fileVector.get(i).getName()+"大小為:"+fileVector.get(i).length()); FileUtil.zipFileFun(fileVector.get(i),root,zos); } //壓縮完成以後必須要在此處執行關閉 否則下載檔案會有問題 if(zos != null){ zos.closeEntry(); zos.close(); } byte[] bt = new byte[10*1024]; int size = 0; bis = new BufferedInputStream(new FileInputStream(zipFilePath),10*1024); while((size=bis.read(bt,10*1024)) != -1){//沒有讀完 out.write(bt,size); } } catch (Exception e) { e.printStackTrace(); }finally {//關閉相關流 try { //避免出異常時無法關閉 if(zos != null){ zos.closeEntry(); zos.close(); } if(bis != null){ bis.close(); } if(out != null){ out.close(); } if(zipFile.exists()){ zipFile.delete();//刪除 } } catch (Exception e2) { System.out.println("流關閉出錯!"); } } return "下載成功"; }
下載輔助工具類
package com.hhwy.fileview.utils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileUtil { /** * 把某個檔案路徑下面的檔案包含資料夾壓縮到一個檔案下 * @param file * @param rootPath 相對地址 * @param zipoutputStream */ public static void zipFileFun(File file,String rootPath,ZipOutputStream zipoutputStream){ if(file.exists()){//檔案存在才合法 if(file.isFile()){ //定義相關操作流 FileInputStream fis = null; BufferedInputStream bis = null; try { //設定資料夾 String relativeFilePath = file.getPath().replace(rootPath+File.separator,""); //建立輸入流讀取檔案 fis = new FileInputStream(file); bis = new BufferedInputStream(fis,10*1024); //將檔案裝入zip中,開始打包 ZipEntry zipEntry; if(!relativeFilePath.contains("\\")){ zipEntry = new ZipEntry(file.getName());//此處值不能重複,要唯一,否則同名檔案會報錯 }else{ zipEntry = new ZipEntry(relativeFilePath);//此處值不能重複,要唯一,否則同名檔案會報錯 } zipoutputStream.putNextEntry(zipEntry); //開始寫檔案 byte[] b = new byte[10*1024]; int size = 0; while((size=bis.read(b,10*1024)) != -1){//沒有讀完 zipoutputStream.write(b,size); } } catch (Exception e) { e.printStackTrace(); }finally { try { //讀完以後關閉相關流操作 if(bis != null){ bis.close(); } if(fis != null){ fis.close(); } } catch (Exception e2) { System.out.println("流關閉錯誤!"); } } } // else{//如果是資料夾 // try { // File [] files = file.listFiles();//獲取資料夾下的所有檔案 // for(File f : files){ // zipFileFun(f,rootPath,zipoutputStream); // } // } catch (Exception e) { // e.printStackTrace(); // } // // } } } /* * 獲取某個資料夾下的所有檔案 */ public static Vector<File> getPathAllFiles(File file,Vector<File> vector){ if(file.isFile()){//如果是檔案,直接裝載 System.out.println("在迭代函式中檔案"+file.getName()+"大小為:"+file.length()); vector.add(file); }else{//資料夾 File[] files = file.listFiles(); for(File f : files){//遞迴 if(f.isDirectory()){ getPathAllFiles(f,vector); }else{ System.out.println("在迭代函式中檔案"+f.getName()+"大小為:"+f.length()); vector.add(f); } } } return vector; } /** * 壓縮檔案到指定資料夾 * @param sourceFilePath 源地址 * @param destinFilePath 目的地址 */ public static String zipFiles(String sourceFilePath,String destinFilePath){ File sourceFile = new File(sourceFilePath); FileInputStream fis = null; BufferedInputStream bis = null; FileOutputStream fos = null; ZipOutputStream zos = null; SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String fileName = dateFormat.format(new Date())+".zip"; String zipFilePath = destinFilePath+File.separator+fileName; if (sourceFile.exists() == false) { System.out.println("待壓縮的檔案目錄:" + sourceFilePath + "不存在."); } else { try { File zipFile = new File(zipFilePath); if (zipFile.exists()) { System.out.println(zipFilePath + "目錄下存在名字為:" + fileName + ".zip" + "打包檔案."); } else { File[] sourceFiles = sourceFile.listFiles(); if (null == sourceFiles || sourceFiles.length < 1) { System.out.println("待壓縮的檔案目錄:" + sourceFilePath + "裡面不存在檔案,無需壓縮."); } else { //讀取sourceFile下的所有檔案 Vector<File> vector = FileUtil.getPathAllFiles(sourceFile,new Vector<File>()); fos = new FileOutputStream(zipFile); zos = new ZipOutputStream(new BufferedOutputStream(fos)); byte[] bufs = new byte[1024 * 10]; for (int i = 0; i < vector.size(); i++) { // 建立ZIP實體,並新增進壓縮包 ZipEntry zipEntry = new ZipEntry(vector.get(i).getName());//檔案不可重名,否則會報錯 zos.putNextEntry(zipEntry); // 讀取待壓縮的檔案並寫進壓縮包裡 fis = new FileInputStream(vector.get(i)); bis = new BufferedInputStream(fis,1024 * 10); int read = 0; while ((read = bis.read(bufs,1024 * 10)) != -1) { zos.write(bufs,read); } } } } } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { // 關閉流 try { if (null != bis) bis.close(); if (null != zos) zos.closeEntry(); zos.close(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } } return fileName; } }
這邊自測試全部可以正常使用,程式碼質量不高
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。