首页 > 解决方案 > 将文件上传到 Firebase 存储时生成访问令牌

问题描述

我正在尝试使用 Firebase 云功能和 PDF。我想通过电子邮件发送 PDF 并将访问令牌保存在 Firebase 数据库中。我的 cloudfunctions 看起来像当前代码:

exports.invoice = functions
  .https
  .onRequest( (req,  res) => {
    const myPdfFile = admin.storage().bucket().file('/test/Arbeitsvertrag-2.pdf');
    const doc = new pdfkit({ margin: 50 });
    const stream = doc.pipe(myPdfFile.createWriteStream());

    doc.fontSize(25).text('Test 4 PDF!', 100, 100);
    doc.end();

 
        
    return res.send('Arbeitsvertrag-2.pdf');

  });

通过此代码,PDF 将存储在 firebase 存储中。 在此处输入图像描述

仅不创建访问令牌。默认情况下有什么方法可以做到这一点?

标签: node.jsfirebasegoogle-cloud-functionsgoogle-cloud-storage

解决方案


您也可以这样做以获取下载 url 并将该 url 包含在电子邮件中。

如果您的文件已存在于 firebase 存储中并且您想要获取公共 url

const bucket = admin.storage().bucket();

const fileInStorage = bucket.file(uploadPath);
const [fileExists] = await fileInStorage.exists();
if (fileExists) {
        const [metadata, response] = await fileInStorage.getMetadata();

        return metadata.mediaLink;
}

如果您想上传文件并同时获取下载网址

    const bucket = admin.storage().bucket();

    // create a temp file to upload to storage
    const tempLocalFile = path.join(os.tmpdir(), fileName);

    const wstream = fs.createWriteStream(tempLocalFile);
    wstream.write(buffer);
    wstream.end();

    // upload file to storage and make it public + creating download token
    const [file, meta] = await bucket.upload(tempLocalFile, {
        destination: uploadPath,
        resumable: false,
        public: true,
        metadata: {
            contentType: 'image/png',
            metadata: {
                firebaseStorageDownloadTokens: uuidV4(),
            },
        },
    });

    //delete temp file
    fs.unlinkSync(tempLocalFile); 

    return  meta.mediaLink;


推荐阅读