简体   繁体   中英

Copy a storage file within a Firebase Cloud Function

I am launching a cloud function in order to replicate one register I have in Firestore. One of the fields is an image, and the function first tries to copy the image and then duplicate the register.

This is the code:

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.');
  }
}

I have tried multiple combinations but this code always fail. For some reason the process of copying the image is failing, I am doing anything wrong?

Thanks.

Using the copy() method in a Cloud Function should work without problem. You don't share any detail about the error you get (I recommend to use catch(error) instead of just catch ) but I can see two potential problems with your code:

  • The file corresponding to originalImage does not exist;
  • The content bucket does not exists in your Cloud Storage instance.

The second problem usually comes from the common mistake of mixing up the concepts of buckets and folders (or directories) in Cloud Storage.

Actually Google Cloud Storage does not have genuine "folders". In the Cloud Storage console, the files in your bucket are presented in a hierarchical tree of folders (just like the file system on your local hard disk) but this is just a way of presenting the files: there aren't genuine folders/directories in a bucket. The Cloud Storage console just uses the different parts of the file paths to "simulate" a folder structure, by using the "/" delimiter character.

This doc on Cloud Storage and gsutil explains and illustrates very well this "illusion of a hierarchical file tree".

So, if you want to copy a file from your default bucket to a content "folder", do as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM