从 firebase 存储下载图像并使用 node.js 云函数添加到 jszip

问题描述

几天来,我一直在为此尝试各种方法,但遇到了困难。我有一些图像存储在 firebase 存储中,我想将它们添加一个 zip 文件中,该文件通过电子邮件发送给其他一些表单。我已经尝试了很多次迭代,但是当 jpeg 文件添加输出的 zip 时,它无法被任何应用程序打开。

这是我的最新版本:

exports.sendEmailPacket = functions.https.onRequest(async (request,response) => {
const userId = request.query.userId;

const image = await admin
    .storage()
    .bucket()
    .file(`images/${userId}`)
    .download();

const zipped = new JSZip();
zipped.file('my-image.jpg',image,{ binary: true });

const content = await zipped.generateAsync({ type: 'nodebuffer' });

// this gets picked up by another cloud function that delivers the email
await admin.firestore()
    .collection("emails")
    .doc(userId)
    .set({
      to: 'myemail@gmail.com',message: {
        attachments: [
          {
            filename: 'test.mctesty.zip',content: Buffer.from(content)
          }
        ]
      }
    });

});

解决方法

经过更多研究后能够弄清楚这一点:

exports.sendEmailPacket = functions.https.onRequest(async (request,response) => {
const userId = request.query.userId;

const image = await admin
    .storage()
    .bucket()
    .file(`images/${userId}`)
    .get(); // get instead of download

const zipped = new JSZip();
zipped.file('my-image.jpg',image[0].createReadStream(),{ binary: true }); // from the 'File' type,call .createReadStream()

const content = await zipped.generateAsync({ type: 'nodebuffer' });

// this gets picked up by another cloud function that delivers the email
await admin.firestore()
    .collection("emails")
    .doc(userId)
    .set({
      to: 'myemail@gmail.com',message: {
        attachments: [
          {
            filename: 'test.mctesty.zip',content: Buffer.from(content)
          }
        ]
      }
    });

});