如何在Firebase函数中获取下载URL
使用Firebase存储存储图像时,图像的URL如下所示: 我想得到这个网址 根据和,我需要使用“storage ref”上的如何在Firebase函数中获取下载URL,firebase,google-cloud-functions,firebase-storage,firebase-admin,Firebase,Google Cloud Functions,Firebase Storage,Firebase Admin,使用Firebase存储存储图像时,图像的URL如下所示: 我想得到这个网址 根据和,我需要使用“storage ref”上的.getDownloadURL()方法。。但可用对象的文档与实际对象不符 当我试图访问下面代码中文档建议的对象上的.getDownloadURL()方法时,我会得到各种属性not found错误 const admin = require('firebase-admin'); admin.initializeApp();
.getDownloadURL()
方法。。但可用对象的文档与实际对象不符
当我试图访问下面代码中文档建议的对象上的.getDownloadURL()
方法时,我会得到各种属性not found错误
const admin = require('firebase-admin');
admin.initializeApp();
admin
.storage()
.bucket()
.upload(imageToBeUploaded.filepath, {
destination: storageFolder,
resumable: false,
metadata: {
metadata: {
contentType: imageToBeUploaded.mimetype
}
}
})
.then((taskSnapshot) => {
// HOW DO I GET THE DOWNLOADABLE URL
})
我尝试了以下方法:
taskSnapshot[1]。getDownloadURL()
admin.storage()
admin.storageRef(storageFolder+'/'+imageFileName).getDownloadURL()
admin.storage()
。。还有其他一些
试错并不是找到使用该方法的“storageRef”
如何获取图像的可下载url?Firebase Admin SDK包装了Google云存储SDK,因此它们的API是相同的。云存储SDK不提供与移动和web SDK完全相同的下载URL
您可以做的是生成一个在功能上类似的
另请参见:我使用的解决方案是首先更改存储桶的访问规则,如下所示:
这意味着URL上不需要令牌才能查看图像
然后我刚刚硬编码了URL:
.then((taskSnapshot) => {
const imageUrl = `https://firebasestorage.googleapis.com/v0/b/` +
`${MY_APP_ID}.appspot.com/o/${imageFileName}?alt=media`;
return imageUrl;
})
对于其他偶然发现这一点的人,下面的代码对我很有用。
其他答案对我的使用不起作用,因为我不想要过期的链接
我仍在学习JS和编程,因此我相信这段代码可以进一步优化,例如:
UploadResponse包含一个文件和一个元数据对象,但我不知道如何直接过滤元数据,因此必须使用该文件才能获取元数据。
const uploadResponse:storage.uploadResponse=wait bucket.upload(tempFilePath);
for(uploadResponse的常量值){
if(值instanceof storage.File){
const metadata=wait value.getMetadata();
const downloadUrl:string=metadata.shift().mediaLink;
}
}
fs.unlinkSync(tempFilePath)代码>小心:使用Firebase函数中生成的签名URL有一个大问题。您可以在上阅读更多内容,但简短的版本是:即使您指定了到期日,它也可能在到期日之前到期,并且您的所有链接都会断开,因为服务帐户的私钥会自动旋转,从而断开已签名的url。对于这个令人沮丧的问题,一个解决办法显然是停止使用serviceAccountId
,然后返回json证书。
.then((taskSnapshot) => {
const imageUrl = `https://firebasestorage.googleapis.com/v0/b/` +
`${MY_APP_ID}.appspot.com/o/${imageFileName}?alt=media`;
return imageUrl;
})