javascript 在Firebase Cloud Function中复制存储文件

pxy2qtax  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(122)

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

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

vmdwslir

vmdwslir1#

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

  • originalImage对应的文件不存在;
  • 您的云存储示例中不存在content存储桶。

第二个问题通常来自云存储中常见的错误,即混淆了bucketfolders(或目录)的概念。
实际上,Google Cloud Storage并没有真正的“文件夹”。在Cloud Storage控制台中,您的存储桶中的文件以文件夹的层次树形式呈现(就像本地硬盘上的文件系统一样),但这只是一种呈现文件的方式:存储桶中并没有真正的文件夹/目录,云存储控制台只是利用文件路径的不同部分,通过“/”分隔符来“模拟”文件夹结构。
云存储上的docgsutil很好地解释和说明了这种“分层文件树的错觉”。
因此,如果您想将文件从默认存储桶复制到内容“文件夹”,请执行以下操作:

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

相关问题