Search code examples
firebasegoogle-cloud-functionsgoogle-cloud-storagejszip

Download image from firebase storage and add to jszip using node.js cloud function


I've been trying various approaches on this for a few days and am hitting a wall. I've got images stored in firebase storage that I want to add to a zip file that gets emailed out with some other forms. I've tried quite a few iterations but, while the jpeg file gets added to the outputted zip, it's not able to be opened by any application.

Here is my latest iteration:

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

});

Solution

  • Was able to figure this out after a bit more research:

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