Search code examples
javascriptfirebasegoogle-cloud-functionsfirebase-storage

Firebase functions download file from storage


I'm using a Firebase function to generate a PDF (pdfkit) with images stored in Storage. I only have the public url of the image. The function and the Storage are part of the same account/project in Firebase.

How can I download the image in a temp location to generate my pdf? I have tried the following code (and some variation but none worked) It cannot find the file/image.

const tmpFilePath = path.join(os.tmpdir(), 'tmp.jpg');
const bucket = admin.storage().bucket();
await bucket.file(imageURL).download({destination: tmpFilePath});
doc.image(tmpFilePath, x, y);
fs.unlinkSync(tmpFilePath);

Solution

  • So just answering my own question for future reference and help others. I could not make the download working with the url so I modify the code to store the local path and use this one instead.

    async function WriteImage(doc:any, storagePath:string, topX:number, topY:number, width:number, height:number, name:string){
        doc.rect(topX, topY, width, height).stroke('#000');
        if(storagePath !== null){
            const tmpPath = path.join(os.tmpdir(), 'tmp.jpg');
            await admin.storage().bucket().file(storagePath).download({destination: tmpPath});
            doc.image(tmpPath, topX, topY, {fit: [width, height]});
            fs.unlinkSync(tmpPath);
    }
    

    }