【工具类】Java实现文件链接集合生成压缩包供前端调用实现文件压缩包下载

需求:有一个存储文件链接的集合,希望将所有文件进行压缩,之后下载为压缩包。

实现效果

在这里插入图片描述
在这里插入图片描述

实现:见代码

后端代码
/**
 * User: yanjun.hou
 * Date: 2024/10/15 13:33
 * Description:
 */

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.StringUtils;
import lombok.Cleanup;
import org.apache.commons.collections4.CollectionUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.*;

public class ZipUtil {
    public static byte[] zipFiles(List<String> fileList) throws SecurityException {
        if (CollectionUtils.isEmpty(fileList)) {
            return null;
        }
        byte[] arr = new byte[0];
        try {
            @Cleanup
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            @Cleanup
            ZipOutputStream zipOut = new ZipOutputStream(outputStream);
            for (String url : fileList) {
                byte[] fileUrlByte = getFileUrlByte(url);
                if (ObjectUtil.isEmpty(fileUrlByte)) {
                    continue;
                }
                // 提取文件名部分
                String fileName = extractFileNameFromUrl(url);
                zipOut.putNextEntry(new ZipEntry(fileName));
                zipOut.write(fileUrlByte);
            }
            zipOut.finish();
            outputStream.flush();
            arr = outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SecurityException("ZipUtil | zipFiles 压缩文件异常");
        }
        return arr;
    }

    /**
     * 获取文件字节
     *
     * @param fileUrl
     * @return
     * @throws Exception
     */
    public static byte[] getFileUrlByte(String fileUrl) throws Exception {
        if (StringUtils.isEmpty(fileUrl)) {
            return null;
        }
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            urlCon.setConnectTimeout(6000);
            urlCon.setReadTimeout(6000);
            int code = urlCon.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK) {
                InputStream is = url.openStream();
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

                byte[] bytes = new byte[1024 * 10];
                int length = 0;
                while ((length = is.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, length);
                }
                outputStream.close();
                is.close();
                return outputStream.toByteArray();
            }

        } catch (IOException e) {
            throw new SecurityException(String.format("文件下载失败, %s", e.getMessage()));
        }
        return null;
    }

    /**
     * 提取文件名部分
     *
     * @param url
     * @return
     */
    private static String extractFileNameFromUrl(String url) {
        if (StringUtils.isEmpty(url)) {
            return null;
        }
        int lastSlashIndex = url.lastIndexOf('/');
        if (lastSlashIndex == -1) {
            return url; // 如果 URL 中没有斜杠,则直接返回 URL
        } else {
            return url.substring(lastSlashIndex + 1);
        }
    }

    public static void main(String[] args) {
        List<String> fileList = new ArrayList<>();
        fileList.add("http://127.0.0.1:10021/profile/2024/10-14/CN332400000012.pdf");
        fileList.add("http://127.0.0.1:10021/profile/2024/10-14/CN332400000013.pdf");
        fileList.add("http://127.0.0.1:10021/profile/2024/10-14/CN332400000014.pdf");
        zipFiles(fileList);
    }
}

前端代码
export function fileBatchDownload(data) {
  return request({
    url: '/fileBatchDownload',
    method: 'post',
    data: data
  })
}
import {fileBatchDownload} from '@/api/xxx'

fileBatchDownload(voucherNumberList).then(res => {
        var raw = window.atob(res.data);
		var uInt8Array = new Uint8Array(raw.length);
		for (var i = 0; i < raw.length; i++) {
			uInt8Array[i] = raw.charCodeAt(i);
		}
		const blob = new Blob([uInt8Array], {
			type: "application/octet-stream",
		});
		const link = document.createElement("a");
		link.style.display = "none";
		link.href = URL.createObjectURL(blob);
		link.download =Date.parse(new Date()) + ".zip";
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
	}).catch(error => {
		console.error('Error downloading files:', error);
});
}				
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

还算善良_

如果对你的工作有所帮助,拜托啦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值