node.js - 将文件上传到 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');
});
仅不创建访问令牌。默认情况下有什么方法可以做到这一点?
解决方案
您也可以这样做以获取下载 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;
推荐阅读
- c# - 使用二维数据和 MVVM 绑定到 DataGrid
- python - 与 tensorflow-gpu 1.4 一起使用的 keras 版本
- c# - 如何在 ASP.NET Core 集成测试中覆盖来自其他容器的 DI 注册
- ios - Swift - CollectionViewCell 边框错误或不完整
- azure-devops - VSTS Windows 机器文件复制 robocopy 未找到
- sql - 如何获取列值的总和作为 SQL 结果集中的新列
- javascript - 如何更改猫头鹰轮播中的视频背景图像?
- javascript - 不稳定的鼠标进入/鼠标离开子菜单
- r - R: na 在 ifelse
- azure - 具有任意磁盘大小的托管磁盘计费