renaming files in Google Cloud Storage?
Asked Answered
G

4

6

Can you rename files in Google Cloud Storage?

I am letting users upload photos, but I want to give them the ability to edit the photo, at least by changing the name they uploaded it with. I am using Javascript through Node.js.

Thanks!

Gale answered 17/7, 2014 at 19:12 Comment(2)
Which API are you using? You'll want to do a copy followed by a delete.Outmarch
i'm using cloud-storage and gcloud, neither of which support copying or moving filesGale
V
3

This command:

gsutil mv gs://my_bucket/olddir gs://my_bucket/newdir

will do the job. If you have a large number of files you need to do a multi-processing move, so use this command:

gsutil -m mv gs://my_bucket/olddir gs://my_bucket/newdir

You can find this information in the docs.

Ventral answered 17/7, 2014 at 19:34 Comment(3)
To be clear: gsutil mv will rename, but it's not an atomic operation: It performs a copy followed by a delete for each object you're renaming.Hessian
but that's from the command line, is there a way to do that from my server-side Node.js code?Gale
To do it from your code you would to do a copy followed by a delete on each object being renamed.Hessian
P
0

Yes. You copy it to a new name with the mv command. Below renames file.html to file.

gsutil mv gs://xxxx/folder/file.html gs://xxxx/folder/file

For more information see Google's gsutil documentation at mv - Move/rename objects.

Plumbery answered 20/1, 2023 at 0:8 Comment(0)
S
0

You can rename a file using the storage.move() method.

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();

const oldFileName = 'path/to/old_file.jpg';
const newFileName = 'path/to/new_file.jpg';

storage
  .bucket(bucketName)
  .file(oldFileName)
  .move(newFileName)
  .then(() => {
    console.log(`File ${oldFileName} was renamed to ${newFileName}.`);
  })
  .catch(err => {
    console.error('Error renaming file:', err);
  });

bucketName is the name of the bucket where the file is located.

oldFileName is the current name of the file.

newFileName is the new name that you want to give the file.

You should have the proper permissions.

Spleeny answered 20/1, 2023 at 1:21 Comment(0)
M
-3

Here is Python function performs a multi-threaded/multi-processing move:

from subprocess import call, CalledProcessError

def rename_object(self, old_dir, new_dir):
    base_cmd = ["gsutil", "-m", "mv"]
    old_path = "gs://{}".format(old_dir)
    new_path = "gs://{}".format(new_dir)
    cmd = base_cmd + [old_path, new_path]
    try:
        call(cmd)
    except CalledProcessError as e:
        print e
Monograph answered 15/12, 2015 at 19:53 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.