簡體   English   中英

我可以通過 Firebase Cloud Functions 壓縮 Firebase 存儲中的文件嗎?

[英]Can I zip files in Firebase Storage via Firebase Cloud Functions?

是否可以使用 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();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM