1. 程式人生 > >java檔案下載功能程式碼(單檔案下載、多檔案批量打包下載)——普遍適用

java檔案下載功能程式碼(單檔案下載、多檔案批量打包下載)——普遍適用

一、前言
  程式設計師在做web等專案的時候,往往都需要新增檔案上傳、下載、刪除的功能,有時是單檔案,有時多檔案批量 操作,而這些功能的程式碼程式設計師可以自己收藏起來當成工具使用,這樣,程式設計師在進行程式設計的時候就會事半功倍 了,那麼接下來的部落格將會介紹各個框架的檔案上傳和下載功能的使用方法。
  這篇部落格的重點放在各個框架都能適用的檔案下載功能程式碼,話不多說,直接切入主題:

二、例項

  1.一般需要加入的jar包:
   commons.fileupload-1.2.1.jar和commons.io-1.4.0.jar,點選下載jar包


   2.方法例項:

    //普通java檔案下載方法,適用於所有框架  
    public String downloadFilesTest(HttpServletRequest request,HttpServletResponse res) throws IOException {
        //獲取檔案根目錄,不同框架獲取的方式不一樣,可自由切換  
        String basePath = request.getSession().getServletContext().getRealPath("/upload/fileDir");  

        //獲取檔名稱(包括檔案格式)  
String fileName = "1.jpg"; //組合成完整的檔案路徑 String targetPath = basePath+File.separator+fileName; //模擬多一個檔案,用於測試多檔案批量下載 String targetPath1 = basePath+File.separator+"2.jpg"; //模擬檔案路徑下再添加個資料夾,驗證窮舉 String targetPath2 = basePath+File.separator+"test"
; System.out.println("檔名:"+fileName); System.out.println("檔案路徑:"+targetPath); //方法1:IO流實現下載的功能 res.setContentType("text/html; charset=UTF-8"); //設定編碼字元 res.setContentType("application/octet-stream"); //設定內容型別為下載型別 res.setHeader("Content-disposition", "attachment;filename="+fileName);//設定下載的檔名稱 OutputStream out = res.getOutputStream(); //建立頁面返回方式為輸出流,會自動彈出下載框 /* //方法1-1:IO位元組流下載,用於小檔案 System.out.println("位元組流下載"); InputStream is = new FileInputStream(targetPath); //建立檔案輸入流 byte[] Buffer = new byte[2048]; //設定每次讀取資料大小,即快取大小 int size = 0; //用於計算快取資料是否已經讀取完畢,如果資料已經讀取完了,則會返回-1 while((size=is.read(Buffer)) != -1){ //迴圈讀取資料,如果資料讀取完畢則返回-1 out.write(Buffer, 0, size); //將每次讀取到的資料寫入客戶端 } is.close(); */ /* //方法1-2:IO字元流下載,用於大檔案 System.out.println("字元流"); File file = new File(targetPath); //建立檔案 FileInputStream fis=new FileInputStream(file); //建立檔案位元組輸入流 BufferedInputStream bis=new BufferedInputStream(fis); //建立檔案緩衝輸入流 byte[] buffer = new byte[bis.available()];//從輸入流中讀取不受阻塞 bis.read(buffer);//讀取資料檔案 bis.close(); out.write(buffer);//輸出資料檔案 out.flush();//釋放快取 out.close();//關閉輸出流 */ /* //方法1-3:將附件中多個檔案進行壓縮,批量打包下載檔案 //建立壓縮檔案需要的空的zip包 String zipBasePath=request.getSession().getServletContext().getRealPath("/upload/zip"); String zipName = "temp.zip"; String zipFilePath = zipBasePath+File.separator+zipName; //建立需要下載的檔案路徑的集合 List<String> filePaths = new ArrayList<String>(); filePaths.add(targetPath); filePaths.add(targetPath1); filePaths.add(targetPath2); //壓縮檔案 File zip = new File(zipFilePath); if (!zip.exists()){ zip.createNewFile(); } //建立zip檔案輸出流 ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zip)); this.zipFile(zipBasePath,zipName, zipFilePath,filePaths,zos); zos.close(); res.setHeader("Content-disposition", "attachment;filename="+zipName);//設定下載的壓縮檔名稱 //將打包後的檔案寫到客戶端,輸出的方法同上,使用緩衝流輸出 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(zipFilePath)); byte[] buff = new byte[bis.available()]; bis.read(buff); bis.close(); out.write(buff);//輸出資料檔案 out.flush();//釋放快取 out.close();//關閉輸出流 */ return null; } /** * 壓縮檔案 * @param zipBasePath 臨時壓縮檔案基礎路徑 * @param zipName 臨時壓縮檔名稱 * @param zipFilePath 臨時壓縮檔案完整路徑 * @param filePaths 需要壓縮的檔案路徑集合 * @throws IOException */ private String zipFile(String zipBasePath, String zipName, String zipFilePath, List<String> filePaths,ZipOutputStream zos) throws IOException { //迴圈讀取檔案路徑集合,獲取每一個檔案的路徑 for(String filePath : filePaths){ File inputFile = new File(filePath); //根據檔案路徑建立檔案 if(inputFile.exists()) { //判斷檔案是否存在 if (inputFile.isFile()) { //判斷是否屬於檔案,還是資料夾 //建立輸入流讀取檔案 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile)); //將檔案寫入zip內,即將檔案進行打包 zos.putNextEntry(new ZipEntry(inputFile.getName())); //寫入檔案的方法,同上 int size = 0; byte[] buffer = new byte[1024]; //設定讀取資料快取大小 while ((size = bis.read(buffer)) > 0) { zos.write(buffer, 0, size); } //關閉輸入輸出流 zos.closeEntry(); bis.close(); } else { //如果是資料夾,則使用窮舉的方法獲取檔案,寫入zip try { File[] files = inputFile.listFiles(); List<String> filePathsTem = new ArrayList<String>(); for (File fileTem:files) { filePathsTem.add(fileTem.toString()); } return zipFile(zipBasePath, zipName, zipFilePath, filePathsTem,zos); } catch (Exception e) { e.printStackTrace(); } } } } return null; }

三、總結

  1. 該方法結合了位元組流、字元流進行單檔案和多檔案打包下載,方法1-1、方法1-2和方法1-3分別屬於不同形式的下載方法,都是在方法1的基礎之上進行的操作,三種方法不可同時使用,需要使用哪種型別的方法則去掉註釋即可;

  2、實踐是檢驗認識真理性的唯一標準,根據程式碼和註釋多進行嘗試,則很快就會明白其中的原理