【问题标题】:Can I zip files in Firebase Storage via Firebase Cloud Functions?我可以通过 Firebase Cloud Functions 压缩 Firebase 存储中的文件吗?
【发布时间】:2019-01-04 22:16:51
【问题描述】:

是否可以使用 Cloud Functions 压缩 Firebase Storage 中的多个文件?

例如,用户上传了 5 张图片,Firebase Cloud Functions 将为这 5 张图片创建一个 zip 文件

【问题讨论】:

标签: node.js firebase google-cloud-functions firebase-storage


【解决方案1】:

我自己在函数中找不到类似场景的 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();
});

【讨论】:

  • 您是否尝试过使用类似的解决方案从 Firebase 存储下载多个文件?由于 firebase 没有任何下载文件夹的解决方案,我需要类似的东西,例如从一个文件夹中获取所有图像,压缩并发送到前端。
  • @MorenoMdz 当然,您可以多次使用 download()archive.append 获得包含少量文件的 zip 文件
  • @YegorAndrosov 您的解决方案也非常适合我。非常感谢!
猜你喜欢
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-05
  • 2019-03-23
  • 2021-11-04
  • 2018-06-26
  • 2017-07-31
  • 1970-01-01
相关资源
最近更新 更多