springmvc批量文件打包成zip下載功能

1.頁面上遍歷checkbox


$("#checkAll").click(function(){
    if(this.checked){    
        $(".thesisCheck").attr("checked", true);   
    }else{    
        $(".thesisCheck").attr("checked", false); 
    }    
});
//批量下載
function plDownload(){
var valArr = new Array; 
var c=0;
$('input[name="selectThesis"]:checked').each(function(i){ 
valArr[i] = $(this).val(); 
c++;
}); 
if(c==0){
alert("請選擇需要下載的文件!");
return;
}else{
var vals = valArr.join(',');//轉換爲逗號隔開的字符串 
if(c==1){
window.location.href = "../thesis/download.do?tcLwId="+vals;
}else{
window.location.href = "../thesis/downloadZip.do?tcLwIds="+vals;
}
}
}



//教師論文批量打包下載

/**

     *  批量打包下載文件生成zip文件下載
     * @param session
     */
    @RequestMapping("downloadZip.do")
    public String downloadFiles(String tcLwIds,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
   {
    List<File> files = new ArrayList<File>();
    System.out.println("需要批量下載的教師論文文件id:tcLwIds:"+tcLwIds);
    if(""==tcLwIds||null==tcLwIds){
    System.out.println("下載的文件不存在");
    return "redirect:tclist.do";
    }
    String[] tcLwIdArray = tcLwIds.split(",");
    for(String tcLwId : tcLwIdArray)
    {
    ThesisCompetitionBean tc = thesisCompetitionService.getTcById(tcLwId);
    File file = new File(request.getSession().getServletContext().getRealPath("/")
  + "/thesisCompetition/uploadFile/" + tc.getThesisUrl());
  files.add(file);
    }
    
    String fileName = UUID.randomUUID().toString() + ".zip";
    //在服務器端創建打包下載的臨時文件
    String outFilePath = request.getSession().getServletContext().getRealPath("/")
+ "/thesisCompetition/uploadFile/";
    createFile(outFilePath,fileName);
    File file = new File(outFilePath+fileName);
    //文件輸出流
    FileOutputStream outStream = new FileOutputStream(file);
    //壓縮流
    ZipOutputStream toClient = new ZipOutputStream(outStream);
    toClient.setEncoding("gbk");
    zipFile(files, toClient);
    toClient.close();
    outStream.close();
    this.downloadFile(file, response,true);
    return null;
   }
    //創建文件
    public void createFile(String path,String fileName){
    //path表示你所創建文件的路徑
    File f = new File(path);
    /*if(!f.exists()){
    f.mkdirs();
    } */
    // fileName表示你創建的文件名;爲txt類型;
    File file = new File(f,fileName);
    if(!file.exists()){
    try {
    file.createNewFile();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }


    }
    
    /**
    * 壓縮文件列表中的文件
    * @param files
    * @param outputStream
    * @throws IOException
    */
    public static void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException,ServletException
    {
    try {
int size = files.size();
// 壓縮列表中的文件
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
} catch (IOException e) {
throw e;
}
}
       /**
* 將文件寫入到zip文件中

* @param inputFile
* @param outputstream
* @throws Exception
*/
        public static void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException,ServletException
        {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream inStream = new FileInputStream(inputFile);
BufferedInputStream bInStream = new BufferedInputStream(
inStream);
ZipEntry entry = new ZipEntry(inputFile.getName());
outputstream.putNextEntry(entry);


final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流爲10M
long streamTotal = 0; // 接受流的容量
int streamNum = 0; // 流需要分開的數量
int leaveByte = 0; // 文件剩下的字符數
byte[] inOutbyte; // byte數組接受文件的數據


streamTotal = bInStream.available(); // 通過available方法取得流的最大字符數
streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分開的數量
leaveByte = (int) streamTotal % MAX_BYTE; // 分開文件之後,剩餘的數量


if (streamNum > 0) {
for (int j = 0; j < streamNum; ++j) {
inOutbyte = new byte[MAX_BYTE];
// 讀入流,保存在byte數組
bInStream.read(inOutbyte, 0, MAX_BYTE);
outputstream.write(inOutbyte, 0, MAX_BYTE); // 寫出流
}
}
// 寫出剩下的流數據
inOutbyte = new byte[leaveByte];
bInStream.read(inOutbyte, 0, leaveByte);
outputstream.write(inOutbyte);
outputstream.closeEntry(); // Closes the current ZIP entry
// and positions the stream for
// writing the next entry
bInStream.close(); // 關閉
inStream.close();
}
} else {
throw new ServletException("文件不存在!");
}
} catch (IOException e) {
throw e;
}
}
      /**
* 下載文件
* @param file
* @param response
*/
      public void downloadFile(File file,HttpServletResponse response,boolean isDelete) {
          try {
              // 以流的形式下載文件。
              BufferedInputStream 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");
              response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));
              toClient.write(buffer);
              toClient.flush();
              toClient.close();
              if(isDelete)
              {
             file.delete();        //是否將生成的服務器端文件刪除
              }
           } 
           catch (IOException ex) {
              ex.printStackTrace();
          }
      }
發佈了151 篇原創文章 · 獲贊 31 · 訪問量 53萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章