springBoot+layui 压缩包 直接下载--或--直接压缩并下载方法

springBoot+layui 压缩包 直接下载–或--直接压缩并下载方法

前端代码
 layer.confirm('您确定要下载 ' + data.fileZipName + ' 吗?', {icon: 3, title: '下载提示'}, function () {
                index = top.layer.msg('文件加载中,请稍候', {icon: 16, time: false, shade: 0.8});
                window.location.href = requestLink + "back/tBatchGroup/download?id=" + data.id;
                layer.closeAll('dialog');
                top.layer.close(index);
            });
控制器代码
 /**
     * 附件下载PDF 压缩包
     * 定位到文件存放地址
     * @param id       主键id
     * @param request
     * @param response
     * @return void
     * @author ZhouXingXing
     * @date 2020-08-15
     */
    @GetMapping("/download")
    public void getDownload(Long id, HttpServletRequest request, HttpServletResponse response) {
        try {
            TBatchGroup entity = this.service.getById(id);
            // 下载本地文件
            String fileName = entity.getFileZipName(); // 文件的默认保存名
            // 读到流中
            String path = "D:\\pdf\\" + entity.getFileZipName() + ".zip";
            InputStream inStream = new FileInputStream(path);// 文件的存放路径
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + ".zip");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
/**
     * 批量下载附件  压缩文件并下载
     * 
     * @param ids      需要下载的id
     * @param soaType
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/plDownload")
//    public void plDownload( Long[] ids, String soaType, HttpServletRequest request, HttpServletResponse response) throws IOException {
    public void plDownload(Long[] ids, String soaType, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            String soaType1 = DicParamUtil.getDicCodeByType("SOA_TYPE", soaType);//数据库字典翻译压缩包名称
            List<String> list = new ArrayList();//需要下载的文件地址
            List<String> fileNameList = new ArrayList();//文件名称
            for (int i = 0; i < ids.length; i++) {
                Long id = ids[i];
                EaAccessory eaAccessory = this.service.selectBusId(id, soaType);//数据库得到文件地址
                if (eaAccessory != null) {
                    fileNameList.add(eaAccessory.getFileName());
                    list.add(eaAccessory.getFileSite()+eaAccessory.getFilePath());//地址添加到list
                }
            }
            String[] files = list.toArray(new String[list.size()]);
            String[] fileName = fileNameList.toArray(new String[fileNameList.size()]);
            String zipPath = zipUtil.downloadAllAttachment(list, soaType1, request, response);

            InputStream inStream = new FileInputStream(zipPath);// 文件的存放路径
            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment; filename=" + soaType1 + ".zip");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            while ((len = inStream.read(b)) > 0)
                response.getOutputStream().write(b, 0, len);
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
工具代码
package com.soa.ump.server.message;/**
 * @auther star
 * @date 2020-07-1920:05
 **/

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *  批量下载
 *
 * @ClassName zipUtil
 * @Ausher star
 * @Date 2020-07-1920:05
 * @Version 1.0
 **/
public class zipUtil {

    //以下为老师打包下载全部学生的报告

    /**
     *
     * @param allFilePath  文件地址
     * @param fileName  压缩包名称
     * @param request
     * @param response
     * @return
     */
    public static String downloadAllAttachment(List<String > allFilePath, String fileName, HttpServletRequest request, HttpServletResponse response) {
//        File dirFile = new File(filePath) ;
//        ArrayList allFilePath = Dir(dirFile);
        List<File> filesList = new ArrayList<>();

        File[] files=new File[allFilePath.size()];
        String path;
        for (int j = 0; j < allFilePath.size(); j++) {
            path=allFilePath.get(j);
            File file = new File(path);
            files[j]=file;
            filesList.add(file);
        }
        fileName = "D://"+fileName;
        return	downLoadFiles(filesList,fileName,request,response);

    }

    //获取文件夹下的所有文件的路径
    public static ArrayList<String> Dir(File dirFile) throws Exception {
        ArrayList<String> dirStrArr = new ArrayList<String>();
        if (dirFile.exists()) {
            //直接取出利用listFiles()把当前路径下的所有文件夹、文件存放到一个文件数组
            File files[] = dirFile.listFiles();
            for (File file : files) {
                //如果传递过来的参数dirFile是以文件分隔符,也就是/或者\结尾,则如此构造
                if (dirFile.getPath().endsWith(File.separator)) {
                    dirStrArr.add(dirFile.getPath() + file.getName());
                } else {
                    //否则,如果没有文件分隔符,则补上一个文件分隔符,再加上文件名,才是路径
                    dirStrArr.add(dirFile.getPath() + File.separator
                            + file.getName());
                }
            }
        }
        return dirStrArr;
    }

    //下载文件
    public static String downLoadFiles(List<File> files,String filePath ,HttpServletRequest request, HttpServletResponse response) {
        try {
            //这里的文件你可以自定义是.rar还是.zip
            filePath = filePath+".zip";
            File file = new File(filePath);
            if (!file.exists()){
                file.createNewFile();
            }else{
                //如果压缩包已经存在则删除后重新打包压缩
                file.delete();
            }
            response.reset();
            //创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);
            /**打包的方法用到ZipOutputStream这样一个输出流,所以这里把输出流转换一下*/
            ZipOutputStream zipOut = new ZipOutputStream(fous);
            /**这个方法接受的就是一个所要打包文件的集合,还有一个ZipOutputStream*/
            zipFiles(files, zipOut);
            zipOut.close();
            fous.close();
            //SummaryRecord/2/3/1536360821177/2018教学班全部附件.zip
            return filePath;

        }catch (Exception e) {
            e.printStackTrace();
            //return "文件下载出错" ;
        }
        return "文件下载出错";
    }

    //把接受的全部文件打成压缩包
    public static void zipFiles(List files,ZipOutputStream outputStream) {

        int size = files.size();

        for(int i = 0; i < size; i++) {

            File file = (File) files.get(i);

            zipFile(file, outputStream);
        }
    }

    //将单个文件打包
    public static void zipFile(File inputFile,ZipOutputStream ouputStream) {

        try {
            if (inputFile.exists()) {
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    //org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    //关闭创建的流对象
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

你可能感兴趣的:(layui+boot,java,intellij,idea,spring,boot)