【问题标题】:Generate acces token when uploading file to firebase storage [duplicate]将文件上传到 Firebase 存储时生成访问令牌 [重复]
【发布时间】:2021-06-25 01:22:34
【问题描述】:

我正在尝试使用 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 存储中。

仅不创建访问令牌。有没有办法默认做到这一点?

【问题讨论】:

  • 查看这个具体答案:stackoverflow.com/a/43764656/209103
  • @FrankvanPuffelen 感谢您的快速回复!但是上传文件成功了,但是如果我通过node js云函数上传,没有创建访问令牌,您对此有解释吗?
  • 如果您查看我在评论中链接的答案(以及下面 Reza 的答案),它会显示如何将元数据添加到存储中的文件以为其提供访问令牌。

标签: node.js firebase google-cloud-functions google-cloud-storage


【解决方案1】:

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

如果您的文件已经存在于 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;

【讨论】:

    猜你喜欢
    • 2020-04-13
    • 2021-01-27
    • 2021-04-07
    • 2020-01-28
    • 1970-01-01
    • 2019-08-18
    • 2021-01-13
    • 2022-08-18
    相关资源
    最近更新 更多