多文件打包下载

一、多文件打包下载

选择多文件,后台压缩zip到服务器,下载到本地,删掉服务器文件

1.js代码

    //工具栏:批量下载(zip)
    $('#templatedownload').bind("click", function(){
        debugger;
        var rows = $('#templatedg').datagrid('getSelections');
        var datas = JSON.stringify(rows);
        if (rows.length>0){
            $.ajax({
                url: encodeURI(ctx + '/report/template/download'),
                type: 'post',
                cache: false,
                contentType: "application/json",
                dataType: "json",
                data:datas,
                success: function (result) {  
                     debugger;
                     var filePath = result.filePath;
                     templateFileDownload( filePath);
                },  
                error: function (e) {  
                    showMsg(result, 'error');
                }  
            });
        }else {
            msgAlert('请选择一笔记录!','info');
        }
    });
    //下载请求
    function templateFileDownload( filePath){
        var downloadForm=$("<form>");//定义一个form表单
        downloadForm.attr("style","display:none");
        downloadForm.attr("target","");
        downloadForm.attr("method","post");
        downloadForm.attr("action",ctx + "/report/template/downloadFile");

        var filePath_inp=$("<input>");
        filePath_inp.attr("type","hidden");
        filePath_inp.attr("name","filePath");
        filePath_inp.attr("value",filePath);

        $("body").append(downloadForm);//将表单放置在web中
        downloadForm.append(filePath_inp);
        downloadForm.submit();//表单提交
    }

2.controller

    /**
     * 下载批量
     */
    @ResponseBody
    @RequestMapping(value = "/download" ,method = RequestMethod.POST )
    public R download(@RequestBody List<ReptTemplateVO> rows,HttpServletRequest request, HttpServletResponse response) {
        String filePath = "";
        try {
            filePath = ZipDownload.downloadFiles(rows, request, response);
        } catch (Exception e) {
            return R.error().put("message", e.getMessage());
        }
        return R.ok().put("filePath", filePath);
    }
    /**
     * 下载批量
     */
    @ResponseBody
    @RequestMapping(value = "/downloadFile" ,method = RequestMethod.POST )
    public void downloadFile(@RequestParam Map<String, Object> params, HttpServletResponse response)  throws Exception {
        String filePath = params.get("filePath").toString();
        filePath = new String(filePath.getBytes("ISO-8859-1"), "UTF-8");
        filePath = URLDecoder.decode(filePath, "UTF-8");
        File file = new File(filePath);
        ZipDownload.downloadZip(file, response);
    }

3.util

package com.itouzi.tam.report.example;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itouzi.tam.report.vo.ReptTemplateVO;

public class ZipDownload {
    public static String downloadFiles(List<ReptTemplateVO> templates,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
       {
           request.setCharacterEncoding("UTF-8");
           String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/jasper");
            
          List<File> files = new ArrayList<File>();
          int index = 0;
          long fileLength = 0;
          for(ReptTemplateVO temp : templates)
          {
             String code = temp.getTplCode();

             String filePath = realPath+"//"+code+".json";
             File file = new File(filePath);
             files.add(file);
             fileLength += file.length();
             index++;

             String filePath1 = realPath+"//"+code+".jasper";
             File file1 = new File(filePath1);
             files.add(file1);
             fileLength += file1.length();
             index++;
          }
          String fileName = System.currentTimeMillis()+".zip";
          //在服务器端创建打包下载的临时文件
          String outFilePath = realPath+"//" + fileName;
          File file = new File(outFilePath);
          //文件输出流
          FileOutputStream outStream = new FileOutputStream(file);
          //压缩流
          ZipOutputStream toClient = new ZipOutputStream(outStream);
          try {
              zipFile(files, toClient);
            } catch (IOException e) {
                toClient.close();
                outStream.close();
                file.delete();        //将生成的服务器端文件删除
                throw new IOException("文件下载失败!");
            } catch (ServletException e) {
                toClient.close();
                outStream.close();
                file.delete();        //将生成的服务器端文件删除
                throw new ServletException("下载文件不存在!");
          }
          toClient.close();
          outStream.close();
          return outFilePath;
        //  downloadZip(file, response);
     }
      /**
       * 压缩文件列表中的文件
       * @param files
       * @param outputStream
       * @throws IOException
       */
      public static void zipFile(List 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
             {
                // inputFile.delete(); 
                 throw new ServletException("文件不存在!");
             }
         }
         catch(IOException e)
         {
             throw e;
         }
    }
      /**
       * 下载打包的文件
       * @param file
       * @param response
       */
      public static void downloadZip(File file,HttpServletResponse response) {
          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=" + file.getName());
              toClient.write(buffer);
              toClient.flush();
              toClient.close();
              file.delete();        //将生成的服务器端文件删除
           } 
           catch (IOException ex) {
              ex.printStackTrace();
          }
      }
}

 

posted @ 2017-11-23 15:33  冠军33  阅读(464)  评论(0编辑  收藏  举报