2021-03-27


前言

使用zip4j下载文件并加密压缩

一、服务器文件批量下载zip加密压缩文件

二、使用步骤

1.引入库

		<dependency>
            <groupId>net.lingala.zip4j</groupId>
            <artifactId>zip4j</artifactId>
            <version>1.3.2</version>
        </dependency>

2.压缩文件并加密

public class ZipUtils {

    public static void createZipFile(String zipPath, String passWd, ArrayList<File> files )
            throws ZipException {
        ZipFile zipFile = new ZipFile(zipPath);
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        parameters.setEncryptFiles(true);
        parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
        parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
        parameters.setPassword(passWd);
        zipFile.addFiles(files, parameters);

    }
}

3.下载压缩文件

    @GetMapping("/exportZip")
    public void exportZip(HttpServletResponse response,Long[] ids) throws Exception {
        //根据id查询要下载的文件路径
        Set<String> list = demoService.selectByIds(ids);
        if(CollectionUtils.isEmpty(atlasList)){
            throw new Exception("无数据");
        }
        //savePath 为服务器上的路径前缀 如‘/opt/app’
        //创建临时文件
        String zipPath = savePath+"/"+System.currentTimeMillis()+".zip";
        //查询当前操作人的手机号,后6位为密码,也可设置随机密码,以短信或者邮件的形式发送给用户
        String mobile = demoService.getMobile(SecurityUtils.getUserId());
        String passWd;
        if(StringUtils.isBlank(mobile)){
            passWd = "123456";
        }else {
            passWd = mobile.substring(5,11);
        }
        ArrayList<File> files = new ArrayList<>();
        //文件地址拼接,如果文件为阿里云等存储,进行下载操作
        list.stream().forEach(
                url-> files.add(new File(savePath+url))
        );
        // 创建加密的ZIP文件
        ZipUtils.createZipFile(zipPath, passWd,files);
        //文件下载
        try {
        	//下载的文件名
            String fileName = URLEncoder.encode(System.currentTimeMillis()+".zip", "UTF-8");
            try {
                FileInputStream fileInputStream = new FileInputStream(zipPath);
                response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
                response.setContentType("application/zip");
                OutputStream outputStream = response.getOutputStream();
                IOUtils.write(IOUtils.toByteArray(fileInputStream), outputStream);
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
            	//删除zip临时文件
                FileUtil.del(zipPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值