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

Get Public URL from file uploaded with firebase-admin

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

我存储了这个规则:

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

我想用这个代码得到一个 public 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 获取文件的 public url?

using Cloud Storage documentation上的示例应用程序代码,您应该可以执行以下代码在上传成功后获得public下载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);
});

或者,如果您需要 public 可访问的下载 URL,请参阅 Cloud Storage NPM 模块中的 which suggests using getSignedUrl(),因为 Admin SDK 不直接支持此功能:

You'll need to generate a signed URL using getSignedURL via the @google-cloud/storage NPM module.

Example:

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>

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

我是怎么找到它的?

我转到了 GCP 控制台、存储。找到上传的文件。单击“复制 URL”。

您可能需要先创建一个文件 Public。我是这样做的:

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

几天来我一直在修改这个问题并意识到

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

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

B) 函数 public 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;