最近项目中遇到 批量下载二维码图片(oss文件)的需求,查看了许多相关博客和资料进行实现。
现将实现过程记录下来
二、代码实现com.aliyun.oss aliyun-sdk-oss 3.6.0
后端:
@Controller
@RequestMapping("/qrcode")
public class QrCodeController extends BaseController{
@RequestMapping(value = "/download",method = RequestMethod.GET )
@RequiresPermissions("qrcode:download")
public String getOssFile(HttpServletRequest request, HttpServletResponse response){
// oss对外服务的访问域名 endpoint以杭州为例,其它region请按实际情况填写,1改为自己的
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建
String accessKeyId = "";
//用户用于加密签名字符串和oss用来验证签名字符串的 密钥
String accessKeySecret = "";
//oss的存储空间
String bucketName = "";
//从数据库中取出要下载的二维码图片路径
//String id = request.getParameter("ids");
//String [] idsArr =id.split(",");
//转换long类型的数组
//Long[] ids = (Long[]) ConvertUtils.convert(idsArr,Long.class);
//List imageList = qrCodeService.getQrCodeListByIds(ids);
//模拟数据库获取oss图片列表
List imageList = new ArrayList<>();
imageList.add("https://ruichuanghuanjing.oss-cn-nanjing.aliyuncs.com/file/20220609/210125193_603.png");
imageList.add("https://ruichuanghuanjing.oss-cn-nanjing.aliyuncs.com/file/20220609/210231316_221.png");
imageList.add("https://ruichuanghuanjing.oss-cn-nanjing.aliyuncs.com/file/20220609/210247235_603.png");
//要下载的文件名(Object Name)字符串,中间用‘,’间隔。文件名从bucket目录开始.5改为自己的
// String key = "focus/item/P8c5z8BKWY1533108107411.png,focus/item/fJ4WmmbM5w1533108018272.png";
try {
// 初始化
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);;
//6改为自己的名称
String fileName = "qr_code.zip";
// 创建临时文件
File zipFile = File.createTempFile("qr_code", ".zip");
FileOutputStream f = new FileOutputStream(zipFile);
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
// 用于将数据压缩成Zip文件格式
ZipOutputStream zos = new ZipOutputStream(csum);
//域名
String oss_domain = commonSettings.getString(Constants.OSS_PIC_URL);
for (String oss_url :imageList){
//得到要下载的文件名(Object Name)字符串
String ossfile = oss_url.replace(oss_domain, "");
// 获取Object,返回结果为OSSObject对象
OSSObject ossObject = ossClient.getObject(bucketName, ossfile);
// 读去Object内容 返回
InputStream inputStream = ossObject.getObjectContent();
// 对于每一个要被存放到压缩包的文件,都必须调用ZipOutputStream对象的putNextEntry()方法,确保压缩包里面文件不同名
zos.putNextEntry(new ZipEntry(ossfile.split("/")[2]));
int bytesRead = 0;
// 向压缩文件中输出数据
while((bytesRead=inputStream.read())!=-1){
zos.write(bytesRead);
}
inputStream.close();
zos.closeEntry(); // 当前文件写完,定位为写入下一条项目
}
zos.close();
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLEncoder.encode(fileName, "utf-8");
fileName = fileName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
fileName = new String(fileName.getBytes(), "ISO8859-1");
}
response.reset();
response.setContentType("text/plain");
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Location", fileName);
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
FileInputStream fis = new FileInputStream(zipFile);
BufferedInputStream buff = new BufferedInputStream(fis);
BufferedOutputStream out=new BufferedOutputStream(response.getOutputStream());
byte[] car=new byte[1024];
int l=0;
while (l < zipFile.length()) {
int j = buff.read(car, 0, 1024);
l += j;
out.write(car, 0, j);
}
// 关闭流
fis.close();
buff.close();
out.close();
ossClient.shutdown();
// 删除临时文件
zipFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
前端调用主要代码:
html5:
var curWwwPath = window.document.location.href;
//获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8083
var localhostPaht = curWwwPath.substring(0, pos);
window.location.href=localhostPaht+"/qrcode/download?ids="+ids.join(",");



