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

时间:2017-11-02 10:24:41

标签: firebase google-cloud-storage firebase-storage firebase-admin

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

我在存储中有这个规则:

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?

4 个答案:

答案 0 :(得分:4)

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);
});

或者,如果您需要可公开访问的下载网址,请参阅this answer,建议您使用云存储NPM模块中的getSignedUrl(),因为管理员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
});

答案 1 :(得分:0)

对我有用的是编写这样的URL:

https://storage.googleapis.com/<bucketName>/<pathToFile>

示例:https://storage.googleapis.com/mybucket.appspot.com/public/myFile.png

我是怎么找到的?

我去了GCP控制台,存储。找到上传的文件。点击“复制URL”。

您可能想先将文件设为“公开”。我是这样做的:

const bucket = seFirebaseService.admin().storage().bucket()
await bucket.file(`public/myFile.png`).makePublic()

答案 2 :(得分:0)

不要将图片上传到任何路径/文件夹,只需将其上传到外部并更改规则

答案 3 :(得分:0)

我一直在修补这个好几天并意识到

A) 对存储桶的正确访问权限是关键:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read;
      allow write: if request.auth != null;
    }
  }
}

B) 功能性公共 URL 就在元数据中(经过测试并有效)。注意访问权限。

  const pdfDoc = printer.createPdfKitDocument(docDefinition);
  const pdfFile = admin
      .storage()
      .bucket()
      .file(newId + '.pdf');

    pdfDoc.pipe(
      pdfFile.createWriteStream({
        contentType: 'application/pdf',
        public: true,
      })
    );
    pdfDoc.end();

    console.log('Get public URL');
    const publicUrl = pdfFile.metadata.mediaLink;