首页 文章

从使用firebase-admin上传的文件中获取公共URL

提问于
浏览
1

我使用firebase-admin和firebase-functions在Firebase存储中上传文件 .

我在存储中有这个规则:

service firebase.storage {
  match /b/{bucket}/o {
    match /images {
      allow read;
      allow write: if false;
    }
  }
}

我希望使用以下代码获取公共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);
      });
});

但我有这个错误 .child is not a function . 如何使用firebase-admin获取文件的公共URL?

1 回答

  • 2

    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不直接支持此功能:

    您需要通过@ google-cloud / storage NPM模块使用getSignedURL生成签名URL . 示例:const gcs = require('@ google-cloud / storage')({keyFilename:'service-account.json'});
    // ...
    const bucket = gcs.bucket(bucket);
    const file = bucket.file(fileName);
    return file.getSignedUrl({
    行动:'读',
    到期日:'03 -09-2491'
    }) . then(signedUrls => {
    // signedUrls [0]包含文件的公共URL
    });

相关问题