关于zip生成文件下载

    1.按文件生成工具类
    public class ZipUtil {

    1. /**<br /> * 打成zip包<br /> * @param targetPath 目标目录<br /> * @param fileNames 文件名<br /> * @param zipname 生成的zip文件名<br /> */<br /> public static void writeZipFile(String targetPath, StringBuffer fileNames, String zipname) {<br /> try {<br /> String[] files = fileNames.toString().split(",");<br /> File file1 = new File(targetPath, zipname + ".zip");<br /> OutputStream os = new BufferedOutputStream(new FileOutputStream(file1));<br /> ZipOutputStream zos = new ZipOutputStream(os);<br /> byte[] buf = new byte[8192];<br /> int len;<br /> for (int i = 0; i < files.length; i++) {<br /> File file = new File(files[i]);<br /> if (!file.isFile()) continue;<br /> ZipEntry ze = new ZipEntry(file.getName());<br /> zos.putNextEntry(ze);<br /> BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));<br /> while ((len = bis.read(buf)) > 0) {<br /> zos.write(buf, 0, len);<br /> }<br /> zos.closeEntry();<br /> }<br />// zos.setEncoding("GBK");<br /> zos.closeEntry();<br /> zos.close();
    2. for (int i = 0; i < files.length; i++) {<br /> System.out.println("------------" + files[i].toString());<br /> File file = new File(files[i]);<br />// file.delete();<br /> }<br /> } catch (IOException e) {<br /> e.printStackTrace();<br /> }<br /> }<br />}

    2.Controller.java 从poi-tl的XWPFTemplate直接写入zip流zos,避免先生成单个word文件、存储浪费空间时间
    @RequestMapping(“/batchExportWordZip”)
    public void batchExportWordZip(YwXjfpQueryModel ywXjfpQueryModel, HttpServletResponse response) {
    String zipFileName = “XJ_” + DateUtil.getCurrentDateTimeSSS() + “.zip”;
    String zipPath = ApplicationConfig.uploadPath + “zip/“;
    try {
    List list = ywXjfpService.findAll(ywXjfpQueryModel);
    if(list.size() == 0){
    response.setContentType(“text/html; charset=UTF-8”); //转码
    PrintWriter out = response.getWriter();
    out.flush();
    out.println(“无记录导出!”);
    return;
    }
    File zipFileDir = new File(zipPath);
    if(!zipFileDir.exists()){
    zipFileDir.mkdirs();
    }
    OutputStream os = new BufferedOutputStream(new FileOutputStream(zipPath + zipFileName));
    ZipOutputStream zos = new ZipOutputStream(os);
    for(YwXjfpQueryModel one : list){
    YwXunjian ywXunjian = ywXunjianService.getByUniqueKey(“fpcd”,one.getFpcd(),YwXunjian.class);
    if(ywXunjian == null) continue;
    YwXunjianQueryModel ywXunjianQueryModel = new YwXunjianQueryModel();
    ywXunjianQueryModel.setXjNo(ywXunjian.getXjNo());
    ResultVo resultVo = findOne(ywXunjianQueryModel, null);
    if(resultVo.getCode() != 0) continue;
    Map data = (Map) resultVo.getData();
    XWPFTemplate template = ywXunjianService.createWord(data);
    if(data.get(“ywXunJian”) != null){
    ywXunjianQueryModel = (YwXunjianQueryModel)data.get(“ywXunJian”);
    }
    if(template != null) {

    1. String docFileName = "XJ_" + ywXunjianQueryModel.getXjDate().substring(0,10).replaceAll("-", "") + "_《" + ywXunjianQueryModel.getStNm() + "》"+ "_" + ywXunjianQueryModel.getXjNo() +".docx";<br /> ZipEntry ze = new ZipEntry(docFileName);<br /> zos.putNextEntry(ze);<br /> template.write(zos);<br /> zos.closeEntry();<br /> PoitlIOUtils.closeQuietlyMulti(template);<br /> }<br /> }<br /> zos.closeEntry();<br /> zos.close();
    2. File file = new File(zipPath + zipFileName);<br /> if (!file.isFile()) {<br /> response.setContentType("text/html; charset=UTF-8"); //转码<br /> PrintWriter out = response.getWriter();<br /> out.flush();<br /> out.println("导出失败,生成zip出错!");<br /> return;<br /> }<br /> FileUtil.downloadFileByBuffer(zipFileName, zipPath + zipFileName, response);
    3. }catch (Exception e){<br /> e.printStackTrace();<br /> }<br /> finally {<br /> DeleteFileUtil.deleteFile(zipPath + zipFileName);<br /> }<br /> }<br /> <br />/***<br /> * 下载文件(防止内存溢出)(推荐)避免使用输入流放入字节数组中<br /> */<br /> public static void downloadFileByBuffer( String newFileName, String path, HttpServletResponse response) {<br /> response.reset();<br /> response.setContentType("application/octet-stream");<br /> try (FileInputStream fileInputStream = new FileInputStream(new File(path));<br /> BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);<br /> BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {<br /> response.setHeader("Content-disposition", "attachment;filename=" + new String(newFileName.getBytes("UTF-8"), "ISO-8859-1"));<br /> FileCopyUtils.copy(bufferedInputStream, bufferedOutputStream);
    4. } catch (Exception e) {<br /> e.printStackTrace();<br /> } finally {
    5. }<br /> }<br />//不推荐<br />public static void downloadFile(String newFileName, String path, HttpServletResponse response) {<br /> try {<br /> // 以流的形式下载文件。<br /> InputStream fis = new BufferedInputStream(new FileInputStream(path));<br /> ** byte[] buffer = new byte[fis.available()]; 不推荐,大文件,内存溢出**<br /> fis.read(buffer);<br /> fis.close();<br /> // 清空response<br /> response.reset();<br /> response.setHeader("Content-disposition", "attachment; filename=" + new String(newFileName.getBytes("UTF-8"), "ISO-8859-1"));<br /> OutputStream toClient = new BufferedOutputStream(response.getOutputStream());<br /> response.setContentType("application/octet-stream;charset=UTF-8");<br /> toClient.write(buffer);<br /> toClient.flush();<br /> toClient.close();<br /> } catch (Exception e) {<br /> e.printStackTrace();<br /> }<br /> }<br />3.前端<br /> <br /> batchExportWord: function () {<br /> var _this = this;<br /> $.confirm("批量下载时间较长,请耐心等待,确认导出吗?<br/>(下载的巡检单为属于巡检任务且已巡检的巡检单)",()=>{<br /> var json = Object.assign({},_this.$data);<br /> json.clzt = 20;<br /> json.sfsyrw = '是';<br /> url = _basePath + "/xunjian/batchExportWordZip?"+json2url(this.$data);<br /> //方法1(推荐): 可以出现loading ,以及错误提示,出错后页面不会空白,无需点击返回<br /> downFile(url);<br /> //方法2: 不能出现loading,出错的提示无法返回,出错后页面不会空白,无需点击返回<br /> // if($("#downIframe").length == 0 ){<br /> // $("body").append("<iframe id='downIframe' name='downIframe' style='display:none' onload='alert(111)' ></iframe>");<br /> // }<br /> // window['downIframe'].location = _basePath + "/xunjian/batchExportWordZip?"+json2url(this.$data);<br /> //方法3: 不能出现loading,出错的提示无法返回,出错后页面会空白,需点击返回,才行<br /> // if($("#downForm").length == 0 ){<br /> // $("body").append("<form id='downForm' method='POST' ></form>");<br /> // }<br /> // $("#downForm").attr("action", _basePath + "/xunjian/batchExportWordZip?"+json2url(this.$data));<br /> // $("#downForm").submit();
    6. //方法4:简单,不能出现loading,出错的提示无法返回,出错后页面会空白,需点击返回,才行<br /> // window.location = _basePath + "/xunjian/batchExportWordZip?"+json2url(this.$data);<br /> })
    7. },<br /> //公共下载方法<br />function downFile(url){<br /> layerShowLoading("正在下载");<br /> var xhr = new XMLHttpRequest();<br /> xhr.open('GET', url, true); // 也可用POST方式<br /> xhr.responseType = "blob";<br /> xhr.onload = function () {<br /> if (this.status === 200) {<br /> var blob = this.response;<br /> if(blob.type.indexOf("text") >= 0){<br /> var fr = new FileReader(); //FileReader可以读取Blob内容<br /> fr.readAsText(blob); //二进制转换成text<br /> fr.onload = function (e) { //转换完成后,调用onload方法<br /> var result = fr.result;<br /> alertM(result);<br /> }<br /> }else {<br /> if (navigator.msSaveBlob == null) {<br /> var a = document.createElement('a');<br /> var headerName = xhr.getResponseHeader("Content-disposition");<br /> a.download = decodeURIComponent(headerName).toLowerCase().replace("attachment;filename=","");<br /> a.href = URL.createObjectURL(blob);<br /> $("body").append(a); // 修复firefox中无法触发click<br /> a.click();<br /> URL.revokeObjectURL(a.href);<br /> $(a).remove();<br /> } else {<br /> navigator.msSaveBlob(blob, decodeURIComponent(headerName).substring(20));<br /> }<br /> }<br /> }<br /> layerCloseLoading();<br /> }<br /> xhr.send();<br />}