【问题标题】:Copy a storage file within a Firebase Cloud Function在 Firebase 云函数中复制存储文件
【发布时间】:2021-04-27 06:16:37
【问题描述】:

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

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

谢谢。

【问题讨论】:

  • copy 中的await ref.set(copy); 是什么?另外,您能否分享一下您的 Cloud Function 的整个代码以及您遇到的错误?
  • @RenaudTarnec 我已经用完整的功能代码更新了这个问题。 'copy' 是要添加到 firestore 的文档。
  • 你能在 catch 块中记录错误吗? catch(error) {…}。另外,content 存储桶是否存在?
  • 既然你提到了它,我不明白存储桶是如何工作的。我已经设置了正确的存储桶名称,一切正常,谢谢。

标签: javascript firebase google-cloud-functions google-cloud-storage firebase-storage


【解决方案1】:

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

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

第二个问题通常来自于混淆 Cloud Storage 中 bucketsfolders(或目录)的概念的常见错误。

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

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

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

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

【讨论】:

    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 2020-08-13
    • 2021-12-20
    • 2019-08-08
    • 2019-02-16
    • 1970-01-01
    • 2018-10-28
    • 2022-12-15
    相关资源
    最近更新 更多