简体   繁体   中英

Can I zip files in Firebase Storage via Firebase Cloud Functions?

Is it possible to compress multiple files in Firebase Storage using Cloud Functions?

For example, there are 5 images uploaded by users and Firebase Cloud Functions will create a zip file for these 5 images

Could not find e2e guide for similar scenario in functions myself, so had to combine solutions for zipping, accessing files in cloud storage etc. See result below:

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM