Disu
Disu

Reputation: 175

Copy file from bucket1 to bucket2 in Google Cloud Storage

I am using the following code to copy file from one storage in my cloud function:

exports.copyFile = functions.storage.object().onFinalize((object) => {
const Storage = require('@google-cloud/storage');
const storage = new Storage();
const srcBucketName = 'bucket1';
const srcFilename = object.name;
const destBucketName = 'bucket2';
const destFilename = 'example.png';

storage
.bucket(srcBucketName)
.file(srcFilename)
.copy(storage.bucket(destBucketName).file(destFilename))
.then(() => {
  console.log(
    `gs://${srcBucketName}/${srcFilename} copied to gs://${destBucketName}/${destFilename}.`
  );
  return console.log('done!');
})
.catch(err => {
  console.error('ERROR:', err);
  })
 });

I am getting following error in log:

ERROR: { ApiError: Not Found
at Object.parseHttpRespBody....}

Not sure what's missing. Any help?

Upvotes: 3

Views: 915

Answers (1)

Disu
Disu

Reputation: 175

const srcBucketName = 'bucket1';  
exports.copyFile = functions.storage.bucket(srcBucketName).object().onFinalize((object) => {
  const Storage = require('@google-cloud/storage');
  const storage = new Storage();  
  const srcFilename = object.name;
  const destBucketName = 'bucket2';
  const destFilename = 'file2';      
  storage
  .bucket(srcBucketName)
  .file(srcFilename)
  .copy(storage.bucket(destBucketName).file(destFilename))
  .then(() => {
    console.log(
      `gs://${srcBucketName}/${srcFilename} copied to gs://${destBucketName}/${destFilename}.`
    );
    return console.log('done!');
  })
  .catch(err => {
    console.error('ERROR:', err);
})
});

Upvotes: 5

Related Questions