java/resteasy批量下载存储在阿里云OSS上的文件,并打包压缩
现在需要从oss上面批量下载文件并压缩打包,搜了很多相关博客,均是缺胳膊少腿,要么是和官网说法不一,要么就压缩包工具类不给出
官方API https://help.aliyun.com/document_detail/32014.html?spm=a2c4g.11186623.6.683.txHAjx

我们采用流式下载,进行简单改装,可以从OSS取到多个文件
思路:ossClient.getObject()获取到文件
再用输入流获取ossObject.getObjectContent(),再利用输入流写入到字节流中,
关闭输入输出流,结束
读取文件接口:
/**
* 根据订单编号查询多个大图路径
* 从OSS取出来多个文件
* 在"D:\\download"进行读取
* 在"D:\\downloadZip"进行压缩
* @param orderNumber
* @return
* @throws Exception
*/
@GET
@Path("readOssFile")
@Produces(MediaType.APPLICATION_JSON)
public PcsResult readOssFile(@QueryParam("orderNumber") String orderNumber) throws Exception {
//orderNumber = 194785
if(orderNumber==null){
logger.error("订单编号不能为空!");
throw new Exception("订单编号不能为空!");
}
List<Map<String,String>> imagePath = myOrderService.queryImageByOrderNumber(orderNumber);
List<String> objectNames = new ArrayList<>();
for (Map<String,String> image:imagePath){
objectNames.add(image.get("imagePath"));
}
// 创建OSSClient实例。
OSSClient ossClient = new OSSClient(END_POINT, ACCESSKEY_ID, ACCESSKEY_SECRET);
//ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
/*
多文件,循环遍历ossClient的Object
*/
for(int i=0;i<objectNames.size();i++) {
OSSObject ossObject = ossClient.getObject(BUCKET_NAME, objectNames.get(i));
File fileDir = new File(fileDirectory);
FileToolUtil.judeDirExists(fileDir);
// 读取文件内容。
// file(内存)----输入流---->【程序】----输出流---->file(内存)
File file = new File(fileDirectory, "addfile"+i+".png");
BufferedInputStream in=null;
BufferedOutputStream out=null;
in=new BufferedInputStream(ossObject.getObjectContent());
out=new BufferedOutputStream(new FileOutputStream(file));
int len=-1;
byte[] b=new byte[1024];
while((len=in.read(b))!=-1){
out.write(b,0,len);
}
//关闭输入输出流
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
} //新建文件夹以备压缩文件存放
File fileDir1 = new File(fileDirectory1);
FileToolUtil.judeDirExists(fileDir1);
//执行压缩操作
ZipUtils.doCompress(fileDirectory, fileDirectory1+"\\" + orderNumber + ".zip");
//数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
ossClient.shutdown();
return newResult(true).setMessage("文件打包成功");
}
写成流,设置response
下载文件接口:
/**
* 流程
* 再将"D:\\download"文件夹删除
* 再将"D:\\download"文件夹删除
* @return
* @throws IOException
*/
@GET
@Path("getOssFile")
@Produces(MediaType.APPLICATION_JSON)
public void getOssFile(@QueryParam("orderNumber") String orderNumber,@Context HttpServletResponse response) throws Exception { //根据存放在fileDirectory1下的压缩文件生成下载请求
OutputStream out = null;
FileInputStream in = null;
try {
in = new FileInputStream(fileDirectory1+"\\" + orderNumber + ".zip");
String fileName = orderNumber + ".zip";
//设置文件输出类型
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename="
+ new String(fileName.getBytes("utf-8"), "ISO8859-1")); byte[] data = FileToolUtil.inputStreamToByte(in);
//设置输出长度
response.setHeader("Content-Length", String.valueOf(data.length));
out = response.getOutputStream();
out.write(data);
out.flush(); //数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
}catch (Exception e){
logger.error(".....getOssFile....", e);
}finally {
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
DeleteFileUtil.delete(fileDirectory);
DeleteFileUtil.delete(fileDirectory1);
}
}
补充:ZipUtil.java
package com.xgt.util; import java.io.*;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; /**
* ZIP压缩工具
*
* @since 1.0
*/
public class ZipUtils { public static final String EXT = ".zip";
private static final String BASE_DIR = ""; // 符号"/"用来作为目录标识判断符
private static final String PATH = "/";
private static final int BUFFER = 1024; /**
* 压缩
*
* @param srcFile
* @throws Exception
*/
public static void compress(File srcFile) throws Exception {
String name = srcFile.getName();
String basePath = srcFile.getParent();
String destPath = basePath + name + EXT;
compress(srcFile, destPath);
} /**
* 压缩
*
* @param srcFile 源路径
* @param destFile 目标路径
* @throws Exception
*/
public static void compress(File srcFile, File destFile) throws Exception { // 对输出文件做CRC32校验
CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(
destFile), new CRC32()); ZipOutputStream zos = new ZipOutputStream(cos); compress(srcFile, zos, BASE_DIR); zos.flush();
zos.close();
} /**
* 压缩文件
*
* @param srcFile
* @param destPath
* @throws Exception
*/
public static void compress(File srcFile, String destPath) throws Exception {
compress(srcFile, new File(destPath));
} /**
* 压缩
*
* @param srcFile 源路径
* @param zos ZipOutputStream
* @param basePath 压缩包内相对路径
* @throws Exception
*/
private static void compress(File srcFile, ZipOutputStream zos,
String basePath) throws Exception {
if (srcFile.isDirectory()) {
compressDir(srcFile, zos, basePath);
} else {
compressFile(srcFile, zos, basePath);
}
} /**
* 压缩
*
* @param srcPath
* @throws Exception
*/
public static void compress(String srcPath) throws Exception {
File srcFile = new File(srcPath); compress(srcFile);
} /**
* 文件压缩
*
* @param srcPath 源文件路径
* @param destPath 目标文件路径
*/
public static void compress(String srcPath, String destPath)
throws Exception {
File srcFile = new File(srcPath); compress(srcFile, destPath);
} /**
* 压缩目录
*
* @param dir
* @param zos
* @param basePath
* @throws Exception
*/
private static void compressDir(File dir, ZipOutputStream zos,
String basePath) throws Exception { File[] files = dir.listFiles(); // 构建空目录
if (files.length < 1) {
ZipEntry entry = new ZipEntry(basePath + dir.getName() + PATH); zos.putNextEntry(entry);
zos.closeEntry();
} for (File file : files) { // 递归压缩
compress(file, zos, basePath + dir.getName() + PATH); }
} /**
* 文件压缩
*
* @param file 待压缩文件
* @param zos ZipOutputStream
* @param dir 压缩文件中的当前路径
* @throws Exception
*/
private static void compressFile(File file, ZipOutputStream zos, String dir)
throws Exception { /**
* 压缩包内文件名定义
*
* <pre>
* 如果有多级目录,那么这里就需要给出包含目录的文件名
* 如果用WinRAR打开压缩包,中文名将显示为乱码
* </pre>
*/
ZipEntry entry = new ZipEntry(dir + file.getName()); zos.putNextEntry(entry); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
file)); int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
zos.write(data, 0, count);
}
bis.close(); zos.closeEntry();
} public static void doCompress(String srcFile, String zipFile) throws IOException {
doCompress(new File(srcFile), new File(zipFile));
} /**
* 文件压缩
* @param srcFile 目录或者单个文件
* @param zipFile 压缩后的ZIP文件
*/
public static void doCompress(File srcFile, File zipFile) throws IOException {
ZipOutputStream out = null;
try {
out = new ZipOutputStream(new FileOutputStream(zipFile));
doCompress(srcFile, out);
} catch (Exception e) {
throw e;
} finally {
out.close();//记得关闭资源
}
} public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
doCompress(new File(filelName), out);
} public static void doCompress(File file, ZipOutputStream out) throws IOException{
doCompress(file, out, "");
} public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
if ( inFile.isDirectory() ) {
File[] files = inFile.listFiles();
if (files!=null && files.length>0) {
for (File file : files) {
String name = inFile.getName();
if (!"".equals(dir)) {
name = dir + "/" + name;
}
ZipUtils.doCompress(file, out, name);
}
}
} else {
ZipUtils.doZip(inFile, out, dir);
}
} public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
String entryName = null;
if (!"".equals(dir)) {
entryName = dir + "/" + inFile.getName();
} else {
entryName = inFile.getName();
}
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry); int len = 0 ;
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(inFile);
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
out.flush();
}
out.closeEntry();
fis.close();
} public static void main(String[] args) throws IOException {
doCompress("E:\\py交易\\download", "E:\\py交易\\download\\效果图批量下载.zip");
} }
FileToolUtil.java
package com.xgt.util; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.File; public class FileToolUtil {
private static final Logger logger = LoggerFactory.getLogger(FileToolUtil.class);
/**
* @author cjy
* @date 2018/6/5 14:35
* @param file
* @return
*/
// 判断文件夹是否存在
public static void judeDirExists(File file) { if (file.exists()) {
if (file.isDirectory()) {
System.out.println("dir exists");
} else {
System.out.println("the same name file exists, can not create dir");
}
} else {
System.out.println("dir not exists, create it ...");
file.mkdir();
} } }
java/resteasy批量下载存储在阿里云OSS上的文件,并打包压缩的更多相关文章
- 关于 tp5.0 阿里云 oss 上传文件操作
tp5.0 结合阿里云oss 上传文件 1.引入 oss 的空间( composer install 跑下第三方拓展包及核心代码包) 备注:本地测试无误,放到线上有问题 应该是移动后的路劲(相对于服 ...
- TP5+阿里云OSS上传文件第三节,实现淘宝上传商品图片
**TP5+阿里云OSS上传文件第三节,实现淘宝上传商品图片首先我们来看看淘宝的功能和样式:** 之后看看制作完成的演示:(由于全部功能弄成GIF有点大,限制上传大小好像在1M之内,压缩之后也有1.9 ...
- 使用阿里云OSS上传文件
本文介绍如何利用Java API操作阿里云OSS对象存储. 1.控制台操作 首先介绍一下阿里云OSS对象存储的一些基本概念. 1.1 进入对象存储界面 登录阿里云账号,进入对象存储界面,如图所示. 进 ...
- 如何获取阿里云OSS上每个文件夹的大小
原文 https://help.aliyun.com/document_detail/88458.html?spm=a2c4g.11186623.2.11.792462b15oU02q OSS文件按照 ...
- 阿里云OSS上传文件本地调试跨域问题解决
问题描述: 最近后台说为了提高上传效率,要前端直接上传文件到阿里云,而不经过后台.因为在阿里云服务器设置的允许源(region)为某个固定的域名下的源(例如*.cheche.com),直接在本地访问会 ...
- 阿里云OSS 上传文件SDK
Aliyun OSS SDK for C# 上传文件 另外:查找的其他实现C#上传文件功能例子: 1.WPF用流的方式上传/显示/下载图片文件(保存在数据库) (文末有案例下载链接) 2.WPF中利用 ...
- 阿里云 oss 上传文件,js直传,.net 签名,回调
后台签名 添加引用 string dir = string.Format("{0:yyyy-MM-dd}", date) + "/"; OssClient cl ...
- 阿里云oss上传文件如何支持https?
let client = new OSS.Wrapper({ accessKeyId: res.data.accessKeyId, accessKeySecret: res.data.accessKe ...
- 阿里云OSS上传文件demo
1.安装ali-oss npm install ali-oss --save 2.demo 此例中使用到了ElementUI的el-upload组件.因为样式为自定义的 所以没有用element的自动 ...
随机推荐
- 本地连接腾讯云Mysql失败问题
腾讯云主机中MySQL无法远程连接的解决办法 在远程主机上,我开启了 mysql服务,用 phpmyadmin 可以打开,比如说用户名为 root,密码为 123456.不过用 Mysql 客户端远程 ...
- List分组迭代器
说明: 针对长度较大的List对象,可以分组批量进行处理, 如:长度为1000的List对象,可分为10组,每组100条,对数据进行业务逻辑处理... Source /**************** ...
- SCVMM 安装
1.所有的物理机必须在域环境下 2.安装VMM和SQL使用的域账号尽量相同,并且唯一,尽量与管理hyper v主机使用的账号不相同
- 24. 两两交换链表中的节点 leetcode
题目: 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表. 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换. 示例: 给定 1->2->3->4, 你应该返回 ...
- 线程概要 Java
线程 进程和线程的区别 串行:初期的计算机只能串行执行任务,大量时间等待用户输入 批处理:预先将用户的指令集中成清单,批量串行处理用户指令,仍然无法并发执行 进程:进程独占内存空间,保存各自运行状态, ...
- leecode刷题(10)-- 旋转图像
leecode刷题(10)-- 旋转图像 旋转图像 描述: 给定一个 n × n 的二维矩阵表示一个图像. 将图像顺时针旋转 90 度. 说明: 你必须在原地旋转图像,这意味着你需要直接修改输入的二维 ...
- php面向对象编程_1
1, php面向对象编程的三大特征: (1) 封装性,封装就是把抽象出的数据和对数据的操作封装在一起,数据被保护在内部,程序的其它部分只有通过被授权的操作(成员方法)才能对数据进行操作. (2) 继承 ...
- Layout1:Grid(补交作业)
Layout1:Grid 这一节我们来讲解一下一个layout:gird. 首先上一段代码: <Page x:Class="Gridstudy.MainPage" xmlns ...
- HTML-★★★★★JavaScritp简介与语法★★★★★
简介: 1.什么是JavaScript? 它是个脚本语言,作用是使 HTML 页面具有更强的动态和交互性,它需要有宿主文件,它的宿主文件就是html文件. JavaScript 是 Web 的编程语 ...
- L1-2 倒数第N个字符串 (15 分)真坑
给定一个完全由小写英文字母组成的字符串等差递增序列,该序列中的每个字符串的长度固定为 L,从 L 个 a 开始,以 1 为步长递增.例如当 L 为 3 时,序列为 { aaa, aab, aac, . ...