我使用firebase-admin和firebase-functions在Firebase Storage中上传文件。
我在存储中有以下规则:
service firebase.storage {
match /b/{bucket}/o {
match /images {
allow read;
allow write: if false;
}
}
}
我想使用以下代码获取公共网址:
const config = functions.config().firebase;
const firebase = admin.initializeApp(config);
const bucketRef = firebase.storage();
server.post('/upload', async (req, res) => {
// UPLOAD FILE
await stream.on('finish', async () => {
const fileUrl = bucketRef
.child(`images/${fileName}`)
.getDownloadUrl()
.getResult();
return res.status(200).send(fileUrl);
});
});
但是我有此错误
.child is not a function
。如何使用firebase-admin获取文件的公共URL?
最佳答案
从using Cloud Storage documentation上的示例应用程序代码中,您应该能够实现以下代码,以在上传成功后获取公共下载URL:
// Create a new blob in the bucket and upload the file data.
const blob = bucket.file(req.file.originalname);
const blobStream = blob.createWriteStream();
blobStream.on('finish', () => {
// The public URL can be used to directly access the file via HTTP.
const publicUrl = format(`https://storage.googleapis.com/${bucket.name}/${blob.name}`);
res.status(200).send(publicUrl);
});
另外,如果您需要公开访问的下载URL,请参阅this answer,该建议建议从Cloud Storage NPM模块中使用
getSignedUrl()
,因为Admin SDK不直接支持此操作:您需要通过getSignedURL通过
@google-cloud/storage NPM模块。
例:
const gcs = require('@google-cloud/storage')({keyFilename: 'service-account.json'});
// ...
const bucket = gcs.bucket(bucket);
const file = bucket.file(fileName);
return file.getSignedUrl({
action: 'read',
expires: '03-09-2491'
}).then(signedUrls => {
// signedUrls[0] contains the file's public URL
});