Sar*_*Vin 8 google-cloud-storage firebase firebase-storage firebase-admin
我使用 firebase-admin 和 firebase-functions 在 Firebase 存储中上传文件。
我在存储中有这个规则:
service firebase.storage {
match /b/{bucket}/o {
match /images {
allow read;
allow write: if false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用以下代码获取公共 URL:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
但我有这个错误.child is not a function
。如何使用 firebase-admin 获取文件的公共 url?
Gri*_*orr 10
从using Cloud Storage 文档中的示例应用代码中,您应该可以实现以下代码以在上传成功后获取公共下载地址:
// 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);
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要可公开访问的下载 URL,请参阅此答案,其中建议使用getSignedUrl()
Cloud Storage NPM 模块,因为 Admin SDK 不直接支持此功能:
您需要通过 @google-cloud/storage NPM 模块使用getSignedURL生成签名 URL 。
例子:
Run Code Online (Sandbox Code Playgroud)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 });
对我有用的是编写这样的 URL:
https://storage.googleapis.com/<bucketName>/<pathToFile>
Run Code Online (Sandbox Code Playgroud)
示例: https: //storage.googleapis.com/mybucket.appspot.com/public/myFile.png
我是怎么找到的?
我转到 GCP Console、存储。找到上传的文件。单击“复制 URL”。
您可能想首先将文件公开。我是这样做的:
https://storage.googleapis.com/<bucketName>/<pathToFile>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15427 次 |
最近记录: |