首页 > 其他分享 >SpringBoot 文件打包zip,浏览器下载出去

SpringBoot 文件打包zip,浏览器下载出去

时间:2023-04-23 21:34:01浏览次数:34  
标签:浏览器 SpringBoot zip fileName zos import new response

本地文件打包

    @GetMapping("/downloadZip")
    public void downloadZip(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode("资产信息.zip", "UTF-8"));
            ServletOutputStream os = response.getOutputStream();
            ZipOutputStream zos = new ZipOutputStream(os);
            byte[] buf = new byte[1024 * 2];
            //资产附件列表
            List<String> assetInfoAgreementsList = new ArrayList<String>() {{
                this.add("/Users/chenyanbin/Desktop/code/ABS/2023/04/13/test三方验收单.pdf");
                this.add("/Users/chenyanbin/Desktop/code/ABS/2023/04/13/test付款审批表.pdf");
                this.add("/Users/chenyanbin/Desktop/code/ABS/2023/04/13/test合同关键页.pdf");
                this.add("/Users/chenyanbin/Desktop/1.pdf");
            }};
            for (String fileName : assetInfoAgreementsList) {
                    File f = new File(fileName);
                    //判断文件是否存在
                    if (f.exists()) {
                        zos.putNextEntry(new ZipEntry("资产附件\\"+fileName.substring(fileName.lastIndexOf("/") + 1)));
                        FileInputStream fis = new FileInputStream(f);
                        //使用字节缓冲输入流
                        BufferedInputStream bis = new BufferedInputStream(fis);
                        int len;
                        while ((len = bis.read(buf)) != -1) {
                            zos.write(buf, 0, len);
                        }
                        zos.closeEntry();
                        bis.close();
                    }
            }
            //资产文件列表
            List<String> attachmentsList = new ArrayList<String>() {{
                this.add("/Users/chenyanbin/Desktop/code/ABS/xxx平台资产服务接口.pdf");
                this.add("/Users/chenyanbin/Desktop/1.jpg");
            }};
            for (String fileName : attachmentsList) {
                    File f = new File(fileName);
                    if (f.exists()) {
                        zos.putNextEntry(new ZipEntry("资产文件\\" + fileName.substring(fileName.lastIndexOf("/") + 1)));
                        FileInputStream fis = new FileInputStream(f);
                        //使用字节缓冲输入流
                        BufferedInputStream bis = new BufferedInputStream(fis);
                        int len;
                        while ((len = bis.read(buf)) != -1) {
                            zos.write(buf, 0, len);
                        }
                        zos.closeEntry();
                        bis.close();
                    }
            }
            zos.closeEntry();
            //必须要执行 zos.finish(); close()时内部会调用finish()
            zos.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("资产信息下载zip异常:{}", e);
        }
    }

远程url文件打包

工具类

package com.ybchen.utils;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName ZipUtils
 * @Description zip工具类
 * @Author Alex
 * @Date 2023/4/23 下午8:55
 * @Version 1.0
 */
@Slf4j
public class ZipUtils {

    /**
     * 通过url下载zip
     * @param response 响应流
     * @param urls url文件路径集合
     * @param zipName xxx.zip
     */
    public static void urlDownloadToZip(HttpServletResponse response, List<String> urls, String zipName) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(bos);
            for (String oneFile : urls) {
                byte[] bytes = getFileFromURL(oneFile);
                zos.putNextEntry(new ZipEntry(parseFileName(oneFile)));
                zos.write(bytes, 0, bytes.length);
                zos.closeEntry();
            }
            zos.close();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(zipName, "UTF-8"));
            OutputStream os = response.getOutputStream();
            os.write(bos.toByteArray());
            os.close();
        } catch (FileNotFoundException ex) {
            log.error("FileNotFoundException", ex);
        } catch (Exception ex) {
            log.error("Exception", ex);
        }
    }

    private static Pattern pattern = Pattern.compile("\\S*[?]\\S*");

    /*
     * 解析url的文件名称
     */
    private static String parseFileName(String url) {

        Matcher matcher = pattern.matcher(url);

        String[] spUrl = url.toString().split("/");
        int len = spUrl.length;
        String endUrl = spUrl[len - 1];

        if (matcher.find()) {
            String[] spEndUrl = endUrl.split("\\?");
            return spEndUrl[0].split("\\.")[0] + "." + spEndUrl[0].split("\\.")[1];
        }
        return endUrl.split("\\.")[0] + "." + endUrl.split("\\.")[1];
    }

    /**
     * 根据文件链接把文件下载下来并且转成字节码
     *
     * @param urlPath url路径
     * @return
     */
    public static byte[] getFileFromURL(String urlPath) {
        byte[] data = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlPath);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            // conn.setDoOutput(true);
//            conn.setRequestMethod("GET");
            conn.setConnectTimeout(6000);
            is = conn.getInputStream();
            if (conn.getResponseCode() == 200) {
                data = readInputStream(is);
            } else {
                data = null;
            }
        } catch (MalformedURLException e) {
            log.error("MalformedURLException", e);
        } catch (IOException e) {
            log.error("IOException", e);
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                log.error("IOException", e);
            }
            conn.disconnect();
        }
        return data;
    }


    private static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        try {
            while ((length = is.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
        } catch (IOException e) {
            log.error("IOException", e);
        }
        byte[] data = baos.toByteArray();
        try {
            is.close();
            baos.close();
        } catch (IOException e) {
            log.error("IOException", e);
        }
        return data;
    }
}

调用

    @GetMapping("/testDownloadZip")
    public void testDownloadZip(HttpServletResponse response) {
        try {
            List<String> urlList = new ArrayList<>();
            urlList.add("https://chenyanbin.oss-cn-hangzhou.aliyuncs.com/20210103/1.png");
            urlList.add("https://pic.cnblogs.com/face/1854114/20221126134321.png");
            urlList.add("https://files.cnblogs.com/files/chenyanbin/redeploy-rancher2-workload.zip?t=1682071754&download=true");
            ZipUtils.urlDownloadToZip(response, urlList, "测试.zip");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

标签:浏览器,SpringBoot,zip,fileName,zos,import,new,response
From: https://www.cnblogs.com/chenyanbin/p/17347823.html

相关文章

  • SpringBoot+React 前后端分离
    SpringBoot+React前后端分离写个转发数据的小工具,本来只想开个SpringBoot服务带个页面,但感觉有点难受,正好之前研究了React,尝试一下前后端分离。后端简单用SpringBoot起个服务,写个接口处理请求:@RestController@RequestMapping("/data")publicclassDataController{......
  • 基于SpringBoot+Vue的音乐网站
    本次项目是基于SpringBoot+Vue的前后端分离项目,旨在熟练相关框架,掌握相关技术,拓展个人知识面。音乐来源:本地用户页面:Web项目亮点:根据歌词、音乐旋律、定位时间线(老师的意见)确定好方向,开始项目、收集资料、准备相关的开发环境和软件等。了解项目的结构与逻辑,确定基本功能,需求......
  • springboot~关于md5签名引发的问题
    事实是这样的,我有个接口,这个接口不能被篡改,于是想到了比较简单的md5对url地址参数进行加密,把这个密码当成是sign,然后服务端收到请求后,使用相同算法也生成sign,两个sign相同就正常没有被篡改过。问题的出现接口中的参数包括userId,extUserId,时间,其中extUserId字符编码,中间会有+......
  • springboot集成JWT token验证
    登录模式基于session登录基于session的登录(有回话状态),用户携带账号密码发送请求向服务器,服务器进行判断,成功后将用户信息放入session,用户发送请求判断session中是否有用户信息,有的话放行,没有的话进行拦截,但是考虑到时App产品,牵扯到要判断用户的session,需要sessionID,还要根据sess......
  • Springboot yml配置参数加密 ,jasypt自定义解密器
    原文链接:https://www.cnblogs.com/JCcccit/p/16868137.html前言 最近项目组开始关注一些敏感数据的明文相关的事宜,其实这些东西也是都有非常成熟的解决方案。既然最近着手去解决这些事情,那么也顺便给还未了解的大伙普及一下。Springbootyml配置参数数据加密(数据加密篇......
  • springboot使用mybatis应用clickhouse
    一、clickhouse,说白了还是数据库,不一样的是clickhouse是列式存储,和传统的MySQL行式存储不同的地方在于,查询和所储。1)查询,行式和列式的区别,图形说明说明:理解上来说,行式对于一条数据的完整性索引会更快。而列式对于统计和查询指定数据会更加块。2)数据......
  • Springboot提高
    全局异常处理器未做处理的情况:当我没没有做任何异常处理时,mapper接口操作数据库出错时,会将异常向上抛给ServiceService中的异常会往上抛给controllercontroller会将异常抛给框架响应给浏览器一个JSON格式的数据这个数据并不符合我们统一响应结果的规范如何处理?方案一:......
  • Java__SpringBoot与Vue连接
    SpringBoot与Vue注解RequestMapping("/dir/")创建一个方便前端调用的接口目录/接口函数,前端可以获取到函数返回的数据@RestController@RequestMapping("/dir/")publicclassBotInfoController{@RequestMapping("getinfo/")publicMap<String,String>GetI......
  • SpringBoot 集成 Quartz + MySQL
    Quartz简单使用JavaSpringBoot中,动态执行bean对象中的方法源代码地址=>https://gitee.com/VipSoft/VipBoot/tree/develop/vipsoft-quartz工作原理解读只要配置好DataSourceQuartz会自动进行表的数据操作,添加QuartzJob任务保存QRTZ_JOB_DETAILS、QRTZ_TRIGGERS=>QR......
  • Java SpringBoot 7z 压缩、解压
    JavaSpringBoot7z压缩、解压JavaSpringBoot7z压缩、解压cmd7z文件压缩7z压缩测试添加依赖<dependency><groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>1.12</versi......