微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

复制 Firebase 云函数中的存储文件

如何解决复制 Firebase 云函数中的存储文件

我正在启动一项云功能,以复制我在 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.');
  }
}

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

谢谢。

解决方法

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

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

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

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

Cloud Storage 上的这个 docgsutil 很好地解释和说明了这种“分层文件树的错觉”。

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

await admin.storage().bucket().file(`content/${originalImage}`).copy(
  admin.storage().bucket().file(`content/${id}`)
);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。