首页 > 解决方案 > 我可以通过 Firebase Cloud Functions 压缩 Firebase 存储中的文件吗?

问题描述

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

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

标签: node.jsfirebasegoogle-cloud-functionsfirebase-storage

解决方案


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

推荐阅读