zoukankan      html  css  js  c++  java
  • Java压缩多个文件并导出

    controller层:

    /**
         * 打包压缩下载文件
         */
        @RequestMapping(value = "/downLoadZipFile")
        public void downLoadZipFile(HttpServletResponse response) throws IOException{
            String zipName = "myfile.zip";
            List<FileBean> fileList = fileService.getFileList();//查询数据库中记录
            response.setContentType("APPLICATION/OCTET-STREAM");  
            response.setHeader("Content-Disposition","attachment; filename="+zipName);
            ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
            try {
                for(Iterator<FileBean> it = fileList.iterator();it.hasNext();){
                    FileBean file = it.next();
                    ZipUtils.doCompress(file.getFilePath()+file.getFileName(), out);
                    response.flushBuffer();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                out.close();
            }
        }

    如果需要支持跨域,在controller中添加代码:

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Method", "POST,GET");

    压缩工具类:

    package com.m2plat.puhui.utils;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.*;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    /**
     * 文件压缩工具类
     * Created by xiangzh on 2018/11/20.
     */
    public class ZipUtils {
    
        private static Logger logger = LoggerFactory.getLogger(ZipUtils.class);
    
        private ZipUtils(){
        }
    
        public static void doCompress(String srcFile, String zipFile) throws IOException {
            doCompress(new File(srcFile), new File(zipFile));
        }
    
        /**
         * 文件压缩
         * @param srcFile 目录或者单个文件
         * @param zipFile 压缩后的ZIP文件
         */
        public static void doCompress(File srcFile, File zipFile) throws IOException {
            ZipOutputStream out = null;
            try {
                out = new ZipOutputStream(new FileOutputStream(zipFile));
                doCompress(srcFile, out);
            } catch (Exception e) {
                throw e;
            } finally {
                out.close();//记得关闭资源
            }
        }
    
        public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
            doCompress(new File(filelName), out);
        }
    
        public static void doCompress(File file, ZipOutputStream out) throws IOException{
            doCompress(file, out, "");
        }
    
        public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
            if ( inFile.isDirectory() ) {
                File[] files = inFile.listFiles();
                if (files!=null && files.length>0) {
                    for (File file : files) {
                        String name = inFile.getName();
                        if (!"".equals(dir)) {
                            name = dir + "/" + name;
                        }
                        ZipUtils.doCompress(file, out, name);
                    }
                }
            } else {
                ZipUtils.doZip(inFile, out, dir);
            }
        }
    
        public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
            String entryName = null;
            if (!"".equals(dir)) {
                entryName = dir + "/" + inFile.getName();
            } else {
                entryName = inFile.getName();
            }
            ZipEntry entry = new ZipEntry(entryName);
            out.putNextEntry(entry);
    
            int len = 0 ;
            byte[] buffer = new byte[1024];
            FileInputStream fis = new FileInputStream(inFile);
            while ((len = fis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
                out.flush();
            }
            out.closeEntry();
            fis.close();
        }
    
        public static void doZip(InputStream in ,ZipOutputStream out, String entryName) throws IOException {
            logger.info("---添加InputStream到压缩文件,InputStream大小:{}",in.available());
            ZipEntry entry = new ZipEntry(entryName);
            out.putNextEntry(entry);
            int len = 0 ;
            byte[] buffer = new byte[1024*5];
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
                out.flush();
            }
            out.closeEntry();
            in.close();
        }
    
        public static void main(String[] args) throws IOException {
            doCompress("D:/excel/puhui/1", "D:/附件.zip");
        }
    
    }

    其他:spring mvc 下载普通单个文件的方法:

    @RequestMapping(value = "/downloadFile")
        @ResponseBody
        public void downloadFile (HttpServletResponse response) {
              OutputStream os  = null;
              try {
           os = response.getOutputStream();
           File file = new File("D:/javaweb/demo.txt");
           // Spring工具获取项目resources里的文件
           File file2 = ResourceUtils.getFile("classpath:shell/init.sh");
                if(!file.exists()){
              return;
           }
                response.reset();
                response.setHeader("Content-Disposition", "attachment;filename=demo.txt");
                response.setContentType("application/octet-stream; charset=utf-8");
                os.write(FileUtils.readFileToByteArray(file));
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                IOUtils.closeQuietly(os);
            }
            
        }

    补充,另外一种 利用 ResponseEntity<byte[]> 实现下载单个文件的方法:

    /**
         * Spring下载文件
         * @param request
         * @throws IOException 
         */
        @RequestMapping(value="/download")
        public ResponseEntity<byte[]> download(HttpServletRequest request) throws IOException{
         // 获取项目webapp目录路径下的文件
            String path = request.getSession().getServletContext().getRealPath("/");
            File file = new File(path+"/soft/javaweb.txt");
            HttpHeaders headers = new HttpHeaders();  
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "javaweb.txt");
            return new ResponseEntity<byte[]>(org.apache.commons.io.FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
        }
      
       <a target="_blank" href="/download">点击下载</a>

    参考:

    Java实现zip压缩多个文件下载

  • 相关阅读:
    angularIO 路由守卫
    vue-property-decorator用法
    windows mysql 忘记密码
    OSPF 做负载均衡
    NLB 部署网络负载平衡
    flexible.js 布局详解
    python setup.py 构建
    python Zope.interface安装使用
    lnmp菜单
    linux下的文件删除原理
  • 原文地址:https://www.cnblogs.com/Jason-Xiang/p/9990549.html
Copyright © 2011-2022 走看看