node.js - 我可以通过 Firebase Cloud Functions 压缩 Firebase 存储中的文件吗?
问题描述
是否可以使用 Cloud Functions 压缩 Firebase 存储中的多个文件?
例如,用户上传了 5 张图片,Firebase Cloud Functions 将为这 5 张图片创建一个 zip 文件
解决方案
我自己在函数中找不到类似场景的 e2e 指南,因此必须结合压缩、访问云存储中的文件等解决方案。请参见下面的结果:
import * as functions from 'firebase-functions';
import admin from 'firebase-admin';
import archiver from 'archiver';
import { v4 as uuidv4 } from 'uuid';
export const createZip = functions.https.onCall(async () => {
const storage = admin.storage();
const bucket = storage.bucket('bucket-name');
// generate random name for a file
const filePath = uuidv4();
const file = bucket.file(filePath);
const outputStreamBuffer = file.createWriteStream({
gzip: true,
contentType: 'application/zip',
});
const archive = archiver('zip', {
gzip: true,
zlib: { level: 9 },
});
archive.on('error', (err) => {
throw err;
});
archive.pipe(outputStreamBuffer);
// use firestore, request data etc. to get file names and their full path in storage
// file path can not start with '/'
const userFilePath = 'user-file-path';
const userFileName = 'user-file-name';
const userFile = await bucket.file(userFilePath).download();
archive.append(userFile[0], {
name: userFileName, // if you want to have directory structure inside zip file, add prefix to name -> /folder/ + userFileName
});
archive.on('finish', async () => {
console.log('uploaded zip', filePath);
// get url to download zip file
await bucket
.file(filePath)
.getSignedUrl({ expires: '03-09-2491', action: 'read' })
.then((signedUrls) => console.log(signedUrls[0]));
});
await archive.finalize();
});
推荐阅读
- html - SAPUI5 响应式表多选集选定记录
- reactjs - Laravel 和 React 身份验证设置
- xcode - IOS 15 标头元素中的 SwiftUI 变得拉伸
- cassandra - 如何从 Cassandra 数据库创建 excel/csv 报告
- ios - 错误域=SSZipArchiveErrorDomain 代码=-1“无法打开 zip 文件”UserInfo={NSLocalizedDescription=无法打开 zip 文件}
- java - 对象引用在 JAVA 中未初始化为 null
- java - 有没有办法从 quarkus 扩展代码中读取主要应用程序资源?
- python - 自定义队列系统的技术建议
- python - 将最终数据从 numpy 导出到 excel
- spring-boot - 一个应用程序的 Keycloak 身份验证客户端无法访问同一领域中的另一个客户端应用程序