在 Firebase Cloud Function 中复制存储文件

svp*_*dga 1 javascript google-cloud-storage firebase google-cloud-platform google-cloud-functions

我正在启动一项云功能,以便复制 Firestore 中的一个寄存器。其中一个字段是图像,该函数首先尝试复制图像,然后复制寄存器。

这是代码:

export async function copyContentFunction(data: any, context: any): Promise<String> {
  if (!context.auth || !context.auth.token.isAdmin) {
    throw new functions.https.HttpsError('unauthenticated', 'Auth error.');
  }

  const id = data.id;
  const originalImage = data.originalImage;
  const copy = data.copy;

  if (id === null || originalImage === null || copy === null) {
    throw new functions.https.HttpsError('invalid-argument', 'Missing mandatory parameters.');
  }

  console.log(`id: ${id}, original image: ${originalImage}`);

  try {
    // Copy the image
    await admin.storage().bucket('content').file(originalImage).copy(
      admin.storage().bucket('content').file(id)
    );

    // Create new content
    const ref = admin.firestore().collection('content').doc(id);
    await ref.set(copy);

    return 'ok';
  } catch {
    throw new functions.https.HttpsError('internal', 'Internal error.');
  }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了多种组合,但此代码总是失败。由于某种原因,复制图像的过程失败了,我做错了什么吗?

谢谢。

Ren*_*nec 6

在云函数中使用该copy()方法应该没有问题。您没有分享有关您收到的错误的任何详细信息(我建议使用catch(error)而不是仅使用catch),但我可以看到您的代码存在两个潜在问题:

  • 对应的文件originalImage不存在;
  • content您的 Cloud Storage 实例中不存在该存储桶。

第二个问题通常来自于混淆Cloud Storage 中的存储桶文件夹(或目录)概念的常见错误。

实际上谷歌云存储并没有真正的“文件夹”。在 Cloud Storage 控制台中,存储桶中的文件以分层文件夹树的形式呈现(就像本地硬盘上的文件系统一样),但这只是呈现文件的一种方式:不存在真正的文件夹/目录在一个桶里。Cloud Storage 控制台仅使用文件路径的不同部分通过使用“/”分隔符来“模拟”文件夹结构。

这篇关于云存储的文档gsutil很好地解释和说明了这种“分层文件树的错觉”。

因此,如果您想将文件从默认存储桶复制到内容“文件夹”,请执行以下操作:

await admin.storage().bucket().file(`content/${originalImage}`).copy(
  admin.storage().bucket().file(`content/${id}`)
);
Run Code Online (Sandbox Code Playgroud)