Uploading, Downloading, and Deleting Objects

This page shows you how to perform basic actions with objects in Google Cloud Storage, including how to upload objects to your bucket, download objects from your bucket, and remove objects from your bucket. For an overview of objects, read the Key Terms and see the Object naming requirements.

Uploading an object

To upload an object to one of your Cloud Storage buckets:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser

  2. In the list of buckets, click on the bucket you want to upload an object to.

  3. Click Upload Files or Upload Folder at the top of the Console.

  4. In the dialog that appears, select the file or folder you want to upload to your bucket.

  5. Click Open.

gsutil

Use the gsutil cp command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

gsutil cp [LOCAL_OBJECT_LOCATION] gs://[DESTINATION_BUCKET_NAME]/

If successful, the response looks like the following example:

Operation completed over 1 objects/58.8 KiB.

Client libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

private void UploadFile(string bucketName, string localPath,
    string objectName = null)
{
    var storage = StorageClient.Create();
    using (var f = File.OpenRead(localPath))
    {
        objectName = objectName ?? Path.GetFileName(localPath);
        storage.UploadObject(bucketName, objectName, null, f);
        Console.WriteLine($"Uploaded {objectName}.");
    }
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

f, err := os.Open("notes.txt")
if err != nil {
	return err
}
defer f.Close()

wc := client.Bucket(bucket).Object(object).NewWriter(ctx)
if _, err = io.Copy(wc, f); err != nil {
	return err
}
if err := wc.Close(); err != nil {
	return err
}

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

InputStream content = new ByteArrayInputStream("Hello, World!".getBytes(UTF_8));
Blob blob = bucket.create(blobName, content, "text/plain");

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The name of the local file to upload, e.g. "./local/path/to/file.txt"
// const filename = "./local/path/to/file.txt";

// Instantiates a client
const storage = Storage();

// Uploads a local file to the bucket
storage
  .bucket(bucketName)
  .upload(filename)
  .then(() => {
    console.log(`${filename} uploaded to ${bucketName}.`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

use Google\Cloud\Storage\StorageClient;

/**
 * Upload a file.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of the object.
 * @param string $source the path to the file to upload.
 *
 * @return Psr\Http\Message\StreamInterface
 */
function upload_object($bucketName, $objectName, $source)
{
    $storage = new StorageClient();
    $file = fopen($source, 'r');
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload($file, [
        'name' => $objectName
    ]);
    printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)

    print('File {} uploaded to {}.'.format(
        source_file_name,
        destination_blob_name))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

# project_id        = "Your Google Cloud project ID"
# bucket_name       = "Your Google Cloud Storage bucket name"
# local_file_path   = "Path to local file to upload"
# storage_file_path = "Path to store the file in Google Cloud Storage"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project: project_id
bucket  = storage.bucket bucket_name

file = bucket.create_file local_file_path, storage_file_path

puts "Uploaded #{file.name}"

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Add the object's data to the request body.
  3. Use cURL to call the JSON API with a POST Object request, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X POST --data-binary @[OBJECT] \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        -H "Content-Type: [OBJECT_CONTENT_TYPE]" \
        "https://www.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=[OBJECT_NAME]"

See Performing a Simple Upload for more information about uploading objects with the JSON API.

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Add the object's data to the request body.
  3. Use cURL to call the XML API with a PUT Object request, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X PUT --data-binary @[OBJECT] \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        -H "Content-Type: [OBJECT_CONTENT_TYPE]" \
        "https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]"

Downloading an object

To download an object from one of your Cloud Storage buckets:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser

  2. In the list of buckets, click on the bucket that contains the object you want to download, and navigate to the object.

  3. Right-click on the object you want to download.

  4. Save the object to your desired local folder.

    For the Chrome browser, the save option appears as Save Link As...

gsutil

Use the gsutil cp command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

gsutil cp gs://[BUCKET_NAME]/[OBJECT_NAME] [OBJECT_DESTINATION]

If successful, the response looks like the following example:

Operation completed over 1 objects/58.8 KiB.

Client libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

private void DownloadObject(string bucketName, string objectName,
    string localPath = null)
{
    var storage = StorageClient.Create();
    localPath = localPath ?? Path.GetFileName(objectName);
    using (var outputFile = File.OpenWrite(localPath))
    {
        storage.DownloadObject(bucketName, objectName, outputFile);
    }
    Console.WriteLine($"downloaded {objectName} to {localPath}.");
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

rc, err := client.Bucket(bucket).Object(object).NewReader(ctx)
if err != nil {
	return nil, err
}
defer rc.Close()

data, err := ioutil.ReadAll(rc)
if err != nil {
	return nil, err
}
return data, nil

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

private void run(Storage storage, BlobId blobId, Path downloadTo) throws IOException {
  Blob blob = storage.get(blobId);
  if (blob == null) {
    System.out.println("No such object");
    return;
  }
  PrintStream writeTo = System.out;
  if (downloadTo != null) {
    writeTo = new PrintStream(new FileOutputStream(downloadTo.toFile()));
  }
  if (blob.getSize() < 1_000_000) {
    // Blob is small read all its content in one request
    byte[] content = blob.getContent();
    writeTo.write(content);
  } else {
    // When Blob size is big or unknown use the blob's channel reader.
    try (ReadChannel reader = blob.reader()) {
      WritableByteChannel channel = Channels.newChannel(writeTo);
      ByteBuffer bytes = ByteBuffer.allocate(64 * 1024);
      while (reader.read(bytes) > 0) {
        bytes.flip();
        channel.write(bytes);
        bytes.clear();
      }
    }
  }
  if (downloadTo == null) {
    writeTo.println();
  } else {
    writeTo.close();
  }
}

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The name of the remote file to download, e.g. "file.txt"
// const srcFilename = "file.txt";

// The path to which the file should be downloaded, e.g. "./local/path/to/file.txt"
// const destFilename = "./local/path/to/file.txt";

// Instantiates a client
const storage = Storage();

const options = {
  // The path to which the file should be downloaded, e.g. "./file.txt"
  destination: destFilename
};

// Downloads the file
storage
  .bucket(bucketName)
  .file(srcFilename)
  .download(options)
  .then(() => {
    console.log(`gs://${bucketName}/${srcFilename} downloaded to ${destFilename}.`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

use Google\Cloud\Storage\StorageClient;

/**
 * Download an object from Cloud Storage and save it as a local file.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of your Google Cloud object.
 * @param string $destination the local destination to save the encrypted object.
 *
 * @return void
 */
function download_object($bucketName, $objectName, $destination)
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination);
    printf('Downloaded gs://%s/%s to %s' . PHP_EOL,
        $bucketName, $objectName, basename($destination));
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

def download_blob(bucket_name, source_blob_name, destination_file_name):
    """Downloads a blob from the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(source_blob_name)

    blob.download_to_filename(destination_file_name)

    print('Blob {} downloaded to {}.'.format(
        source_blob_name,
        destination_file_name))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage to download locally"
# local_path  = "Path to local file to save"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project: project_id
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.download local_path

puts "Downloaded #{file.name}"

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a GET Object request, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X GET \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        -o "[SAVE_TO_LOCATION]" \
        "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]?alt=media"

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API with a GET Object request, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X GET \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        -o "[SAVE_TO_LOCATION]" \
        "https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]"

Deleting an object

To delete an object from one of your Cloud Storage buckets:

Console

  1. Open the Cloud Storage browser in the Google Cloud Platform Console.
    Open the Cloud Storage browser

  2. In the list of buckets, click on the bucket that contains the object you want to delete, and navigate to the object.

  3. Click the checkbox next to the object you want to delete.

  4. Click Delete at the top of the Console.

  5. Click OK in the dialog that appears.

gsutil

Use the gsutil rm command, replacing [VALUES_IN_BRACKETS] with the appropriate values:

gsutil rm gs://[BUCKET_NAME]/[OBJECT_NAME]

If successful, the response looks like the following example:

Operation completed over 1 objects.

Client libraries

C#

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

private void DeleteObject(string bucketName, IEnumerable<string> objectNames)
{
    var storage = StorageClient.Create();
    foreach (string objectName in objectNames)
    {
        storage.DeleteObject(bucketName, objectName);
        Console.WriteLine($"Deleted {objectName}.");
    }
}

Go

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

o := client.Bucket(bucket).Object(object)
if err := o.Delete(ctx); err != nil {
	return err
}

Java

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

BlobId blobId = BlobId.of(bucketName, blobName);
boolean deleted = storage.delete(blobId);
if (deleted) {
  // the blob was deleted
} else {
  // the blob was not found
}

Node.js

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

// Imports the Google Cloud client library
const Storage = require('@google-cloud/storage');

// The name of the bucket to access, e.g. "my-bucket"
// const bucketName = "my-bucket";

// The name of the file to delete, e.g. "file.txt"
// const filename = "file.txt";

// Instantiates a client
const storage = Storage();

// Deletes the file from the bucket
storage
  .bucket(bucketName)
  .file(filename)
  .delete()
  .then(() => {
    console.log(`gs://${bucketName}/${filename} deleted.`);
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

PHP

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an object.
 *
 * @param string $bucketName the name of your Cloud Storage bucket.
 * @param string $objectName the name of your Cloud Storage object.
 * @param array $options
 *
 * @return void
 */
function delete_object($bucketName, $objectName, $options = [])
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->delete();
    printf('Deleted gs://%s/%s' . PHP_EOL, $bucketName, $objectName);
}

Python

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

def delete_blob(bucket_name, blob_name):
    """Deletes a blob from the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(blob_name)

    blob.delete()

    print('Blob {} deleted.'.format(blob_name))

Ruby

For more on installing and creating a Cloud Storage client, refer to Cloud Storage Client Libraries.

# project_id  = "Your Google Cloud project ID"
# bucket_name = "Your Google Cloud Storage bucket name"
# file_name   = "Name of file in Google Cloud Storage to delete"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new project: project_id
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.delete

puts "Deleted #{file.name}"

REST APIs

JSON API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the JSON API with a DELETE Object request, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X DELETE \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]"

XML API

  1. Get an authorization access token from the OAuth 2.0 Playground. Configure the playground to use your own OAuth credentials.
  2. Use cURL to call the XML API with a DELETE Object request, replacing [VALUES_IN_BRACKETS] with the appropriate values:
    curl -X DELETE \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]"

Send feedback about...

Cloud Storage Documentation