首页 > 编程语言 >java 从oss上下载多个图片,压缩并返回给前端下载

java 从oss上下载多个图片,压缩并返回给前端下载

时间:2022-09-07 20:02:44浏览次数:72  
标签:java String zip KeepDirStructure oss param zos new 下载

controller层

 /**
     * 下载图片-->创建文件夹
     * @param params
     * @return
     * @throws Exception
     */
    @PostMapping("/handerImageDownload")
    public AjaxResult handerImageDownload(@RequestParam Map<String, String> params,HttpServletResponse response) {
        try {
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateString = formatter.format(date);
            String airlineName = params.get("airlineName");
            String fileUrl = "D:/DJI_"+dateString+airlineName;
            listFiles("sne","D:\\DJI_"+dateString+airlineName+"\\");
            String fileName = "D:\\offline.zip";
            OutputStream fos2 = response.getOutputStream();
            // 压缩并返回前端
            ZipUtils.toZip(fileUrl,fos2,true);

        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
        return AjaxResult.success();
    }

oss下载图片

/**
     * oss下载图片
     * @param prefix
     * @param directoryPath
     * @return
     * @throws IOException
     */
    public  boolean listFiles(String prefix, String directoryPath) throws IOException {
        // Endpoint以杭州为例,其它Region请按实际情况填写。
//        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录RAM控制台创建RAM账号。
        String accessKeyId = "LTAI5tGbLQCs4xnMV6b33CzZ";
        String accessKeySecret = "RL7hz35wMJ0oPvjrHhefD0z8xOo3sd";

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);



        boolean flag;
        String marker = "";
        do {
            ListObjectsRequest lor = new ListObjectsRequest();
            //指定目录
            lor.setPrefix(prefix);
            lor.setBucketName("snedji");
            //
            lor.setMarker(marker);
            //分页大小
            lor.setMaxKeys(100);
            ObjectListing ol = ossClient.listObjects(lor);
            for (OSSObjectSummary o : ol.getObjectSummaries()) {
                if(!o.getKey().contains("org_")){
                    continue;
                }
                System.out.println(" - " + o.getKey() + "  " + "(size = " + o.getSize() + ")");
                //
                final String path = directoryPath + o.getKey();
                //获取文件对象
                GetObjectRequest gor = new GetObjectRequest("snedji", o.getKey());
                //截取目录 如果目录不存在则创建
                String directoryStr = path.substring(0, path.lastIndexOf("/"));
                File directory = new File(directoryStr);
                if (!directory.exists()) {
                    directory.mkdirs();
                }
                //获取文件流  使用高速缓存 + 数组复制 最大效率输出文件
                try (

                        BufferedInputStream bis = new BufferedInputStream(ossClient.getObject(gor).getObjectContent());
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path))) {
                    int size;
                    byte[] bytes = new byte[1024];
                    while ((size = bis.read(bytes)) != -1) {
                        bos.write(bytes, 0, size);
                    }
                    bos.flush();
                }
            }
            //当前页的最后一个文件
            marker = ol.getNextMarker();
            //是否还有文件
            flag = ol.isTruncated();

        } while (flag);


        ossClient.shutdown();

        return true;
    }

zip下载工具类

package com.pms.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * zip处理工具类
 * 
 * @author LayTao
 */
public class ZipUtils
{

    private static final int  BUFFER_SIZE = 2 * 1024;

    /**
     * 压缩成ZIP 方法1
     * @param srcDir 压缩文件夹路径
     * @param out    压缩文件输出流
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     * 							false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException{

        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            // 这里打成压缩包 name 默认是一级路径 这边不需要 可以设置为空 如果需要 直接设置为:sourceFile.getName()
            compress(sourceFile,zos,"",KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 压缩成ZIP 方法2
     * @param srcFiles 需要压缩的文件列表
     * @param out 	        压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 递归压缩方法
     * @param sourceFile 源文件
     * @param zos		 zip输出流
     * @param name		 压缩后的名称
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     * 							false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if(KeepDirStructure){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }
            }else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        if (StringUtils.isNull(name) || StringUtils.isEmpty(name)){
                            compress(file, zos, file.getName(),KeepDirStructure);
                        }
                        else {
                            compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                        }
                    } else {
                        compress(file, zos, file.getName(),KeepDirStructure);
                    }

                }
            }
        }
    }

}

亲测有效!欢迎提问

标签:java,String,zip,KeepDirStructure,oss,param,zos,new,下载
From: https://www.cnblogs.com/lovexiao/p/16667083.html

相关文章

  • Java注释
    Java注释单行注释两个/后面跟要注释的内容即可,如://我是单行注释多行注释用/**/来包裹住要注释的内容即可,如:/*我是多行注释啊啊啊啊啊啊啊啊啊啊啊啊啊*/文档注......
  • Java数据类型
    Java数据类型介绍java是一门强类型语言,要求变量的使用要严格符合规定,所有变量都必须先定义后才能使用。分类基本数据类型整数类型:byte范围在-128~127之间short范围......
  • java 使用递归遍历文件夹及子文件夹中文件
    //使用递归遍历文件夹及子文件夹中文件publicvoidfilesDirs(Filefile){//File对象是文件或文件夹的路径,第一层判断路径是否为空if(file!=null......
  • JavaWeb学习笔记第三弹
    一、数据库设计1、软件研发步骤2、数据库设计概念建立数据库中的表结构以及表与表之间的关联关系的过程3、数据库设计的步骤表关系:一对一、一对多(多对一)、多对多......
  • java中公平锁非公平锁的区别
    公平锁:多线程按照申请锁的顺序来获取锁,不会出现争抢的情况。非公平锁:多线程不会按照顺序获取锁,会先尝试去争抢锁,有可能后申请的线程比先申请的线程先抢到锁,在高并发情况下......
  • javascript第一天
    JavaScript基础-第1天了解变量、数据类型、运算符等基础概念,能够实现数据类型的转换,结合四则运算体会如何编程。体会现实世界中的事物与计算机的关系理解什么是数......
  • 【over】重学Java se
    踩个坑,因为刚学完ssm框架,着急了解原理,我尝试着去了解spring的源码,后来才发现,没有开发经验,还是别谈了解源码了,好几十万行的代码,在我现在这个阶段来说,不光说看不懂,看的东西也......
  • Logstash深入收集Java日志
    Logstash深入收集Java日志没有修改Json格式在企业中,我们看到tomcat日志遇到异常(exception)一条日志可能是几行或者十几行甚至几十行,组成的,那么,我们需要将多行日志变成......
  • java获取当前日期和前一周、前一月、前一年的日期
    java获取当前日期和前一周、前一月、前一年的日期publicstaticvoidmain(String[]args){SimpleDateFormatformat=newSimpleDateFormat("yyyy-MM-dd......
  • java读取和设置配置文件中的属性参数
    想必大家和我一样经常在项目中读取一些配置文件,因为读取的配置很少,结构简单又不想搞个读取xml,比较麻烦。所以这时大多采取读取.properties配置文件,我们和大名鼎鼎的log4j......