Sube objetos desde un sistema de archivos

En esta página, se muestra cómo subir objetos a tu bucket de Cloud Storage desde tu sistema de archivos local. Un objeto subido consiste en los datos que deseas almacenar junto con los metadatos asociados. Para obtener una descripción general conceptual, incluido cómo elegir el método de carga óptimo en función del tamaño del archivo, consulta Cargas y descargas.

Para obtener instrucciones sobre cómo subir objetos desde la memoria, consulta Sube objetos desde la memoria.

Funciones obligatorias

Para obtener los permisos que necesitas a fin de subir objetos a un bucket, pídele a tu administrador que te otorgue el rol de IAM Usuario de objetos de almacenamiento (roles/storage.objectUser) para el bucket. Este rol predefinido contiene el permiso necesario para subir un objeto a un bucket. Para ver los permisos exactos que son necesarios, expande la sección Permisos requeridos:

Permisos necesarios

  • storage.objects.create
  • storage.objects.delete
    • Este permiso solo es necesario para las cargas que reemplazan un objeto existente.
  • storage.objects.get
    • Este permiso solo es necesario si planeas usar Google Cloud CLI para realizar las tareas en esta página.
  • storage.objects.list
    • Este permiso solo es necesario si planeas usar Google Cloud CLI para realizar las tareas en esta página. Este permiso también es necesario si deseas usar la consola de Google Cloud para verificar los objetos que subiste.

Si planeas usar la consola de Google Cloud para realizar las tareas de esta página, también necesitarás el permiso storage.buckets.list, que no se incluye en el rol Usuario de objetos de Storage (roles/storage.objectUser). Para obtener este permiso, pídele a tu administrador que te otorgue el rol Administrador de almacenamiento (roles/storage.admin) en el proyecto.

También puedes obtener estos permisos con otros roles predefinidos o roles personalizados.

Para obtener más información sobre cómo otorgar roles en los buckets, consulta Usa IAM con buckets.

Subirás un objeto a un bucket.

Sigue los pasos a continuación para subir un objeto a un bucket:

Console

  1. En la consola de Google Cloud, ve a la página Buckets de Cloud Storage.

    Ir a Buckets

  2. En la lista de buckets, haz clic en el nombre del bucket al que deseas subir un objeto.

  3. En la pestaña Objetos para el depósito, realiza una de estas dos acciones:

    • Arrastra y suelta los archivos deseados desde tu escritorio o administrador de archivos en el panel principal de la consola de Google Cloud.

    • Haz clic en el botón Subir archivos, selecciona los archivos que deseas subir en el cuadro de diálogo que aparece y haz clic en Abrir.

Para obtener información sobre cómo ver detalles de errores acerca de operaciones fallidas de Cloud Storage en la consola de Google Cloud, consulta Solución de problemas.

Línea de comandos

Usa el comando gcloud storage cp:

gcloud storage cp OBJECT_LOCATION gs://DESTINATION_BUCKET_NAME

Aquí:

  • OBJECT_LOCATION es la ruta de acceso local a tu objeto. Por ejemplo, Desktop/dog.png

  • DESTINATION_BUCKET_NAME es el nombre del bucket al que subes el objeto. Por ejemplo, my-bucket

Si se ejecuta de forma correcta, la respuesta se parece al siguiente ejemplo:

Completed files 1/1 | 164.3kiB/164.3kiB

Puedes configurar metadatos de objetos de clave fija y personalizada como parte de la carga de objetos mediante marcas de comandos.

Bibliotecas cliente

C++

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C++.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& file_name,
   std::string const& bucket_name, std::string const& object_name) {
  // Note that the client library automatically computes a hash on the
  // client-side to verify data integrity during transmission.
  StatusOr<gcs::ObjectMetadata> metadata = client.UploadFile(
      file_name, bucket_name, object_name, gcs::IfGenerationMatch(0));
  if (!metadata) throw std::move(metadata).status();

  std::cout << "Uploaded " << file_name << " to object " << metadata->name()
            << " in bucket " << metadata->bucket()
            << "\nFull metadata: " << *metadata << "\n";
}

C#

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage C#.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class UploadFileSample
{
    public void UploadFile(
        string bucketName = "your-unique-bucket-name",
        string localPath = "my-local-path/my-file-name",
        string objectName = "my-file-name")
    {
        var storage = StorageClient.Create();
        using var fileStream = File.OpenRead(localPath);
        storage.UploadObject(bucketName, objectName, null, fileStream);
        Console.WriteLine($"Uploaded {objectName}.");
    }
}

Go

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Go.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

// uploadFile uploads an object.
func uploadFile(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	// Open local file.
	f, err := os.Open("notes.txt")
	if err != nil {
		return fmt.Errorf("os.Open: %w", err)
	}
	defer f.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	o := client.Bucket(bucket).Object(object)

	// Optional: set a generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to upload is aborted if the
	// object's generation number does not match your precondition.
	// For an object that does not yet exist, set the DoesNotExist precondition.
	o = o.If(storage.Conditions{DoesNotExist: true})
	// If the live object already exists in your bucket, set instead a
	// generation-match precondition using the live object's generation number.
	// attrs, err := o.Attrs(ctx)
	// if err != nil {
	// 	return fmt.Errorf("object.Attrs: %w", err)
	// }
	// o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})

	// Upload an object with storage.Writer.
	wc := o.NewWriter(ctx)
	if _, err = io.Copy(wc, f); err != nil {
		return fmt.Errorf("io.Copy: %w", err)
	}
	if err := wc.Close(); err != nil {
		return fmt.Errorf("Writer.Close: %w", err)
	}
	fmt.Fprintf(w, "Blob %v uploaded.\n", object)
	return nil
}

Java

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Java.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.IOException;
import java.nio.file.Paths;

public class UploadObject {
  public static void uploadObject(
      String projectId, String bucketName, String objectName, String filePath) throws IOException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The path to your file to upload
    // String filePath = "path/to/your/file"

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request returns a 412 error if the
    // preconditions are not met.
    Storage.BlobWriteOption precondition;
    if (storage.get(bucketName, objectName) == null) {
      // For a target object that does not yet exist, set the DoesNotExist precondition.
      // This will cause the request to fail if the object is created before the request runs.
      precondition = Storage.BlobWriteOption.doesNotExist();
    } else {
      // If the destination already exists in your bucket, instead set a generation-match
      // precondition. This will cause the request to fail if the existing object's generation
      // changes before the request runs.
      precondition =
          Storage.BlobWriteOption.generationMatch(
              storage.get(bucketName, objectName).getGeneration());
    }
    storage.createFrom(blobInfo, Paths.get(filePath), precondition);

    System.out.println(
        "File " + filePath + " uploaded to bucket " + bucketName + " as " + objectName);
  }
}

Node.js

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Node.js.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se sube un objeto individual:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The path to your file to upload
// const filePath = 'path/to/your/file';

// The new ID for your GCS file
// const destFileName = 'your-new-file-name';

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

// Creates a client
const storage = new Storage();

async function uploadFile() {
  const options = {
    destination: destFileName,
    // Optional:
    // Set a generation-match precondition to avoid potential race conditions
    // and data corruptions. The request to upload is aborted if the object's
    // generation number does not match your precondition. For a destination
    // object that does not yet exist, set the ifGenerationMatch precondition to 0
    // If the destination object already exists in your bucket, set instead a
    // generation-match precondition using its generation number.
    preconditionOpts: {ifGenerationMatch: generationMatchPrecondition},
  };

  await storage.bucket(bucketName).upload(filePath, options);
  console.log(`${filePath} uploaded to ${bucketName}`);
}

uploadFile().catch(console.error);

En el siguiente ejemplo, se suben varios objetos de forma simultánea:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of the first GCS file to download
// const firstFilePath = 'your-first-file-name';

// The ID of the second GCS file to download
// const secondFilePath = 'your-second-file-name';

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

// Creates a client
const storage = new Storage();

// Creates a transfer manager client
const transferManager = new TransferManager(storage.bucket(bucketName));

async function uploadManyFilesWithTransferManager() {
  // Uploads the files
  await transferManager.uploadManyFiles([firstFilePath, secondFilePath]);

  for (const filePath of [firstFilePath, secondFilePath]) {
    console.log(`${filePath} uploaded to ${bucketName}.`);
  }
}

uploadManyFilesWithTransferManager().catch(console.error);

En el siguiente ejemplo, se suben todos los objetos con un prefijo común de forma simultánea:

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The local directory to upload
// const directoryName = 'your-directory';

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

// Creates a client
const storage = new Storage();

// Creates a transfer manager client
const transferManager = new TransferManager(storage.bucket(bucketName));

async function uploadDirectoryWithTransferManager() {
  // Uploads the directory
  await transferManager.uploadManyFiles(directoryName);

  console.log(`${directoryName} uploaded to ${bucketName}.`);
}

uploadDirectoryWithTransferManager().catch(console.error);

PHP

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage PHP.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

use Google\Cloud\Storage\StorageClient;

/**
 * Upload a file.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $source The path to the file to upload.
 *        (e.g. '/path/to/your/file')
 */
function upload_object(string $bucketName, string $objectName, string $source): void
{
    $storage = new StorageClient();
    if (!$file = fopen($source, 'r')) {
        throw new \InvalidArgumentException('Unable to open file for reading');
    }
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload($file, [
        'name' => $objectName
    ]);
    printf('Uploaded %s to gs://%s/%s' . PHP_EOL, basename($source), $bucketName, $objectName);
}

Python

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Python.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

En el siguiente ejemplo, se sube un objeto individual:

from google.cloud import storage


def upload_blob(bucket_name, source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The path to your file to upload
    # source_file_name = "local/path/to/file"
    # The ID of your GCS object
    # destination_blob_name = "storage-object-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(destination_blob_name)

    # Optional: set a generation-match precondition to avoid potential race conditions
    # and data corruptions. The request to upload is aborted if the object's
    # generation number does not match your precondition. For a destination
    # object that does not yet exist, set the if_generation_match precondition to 0.
    # If the destination object already exists in your bucket, set instead a
    # generation-match precondition using its generation number.
    generation_match_precondition = 0

    blob.upload_from_filename(source_file_name, if_generation_match=generation_match_precondition)

    print(
        f"File {source_file_name} uploaded to {destination_blob_name}."
    )

En el siguiente ejemplo, se suben varios objetos de forma simultánea:

def upload_many_blobs_with_transfer_manager(
    bucket_name, filenames, source_directory="", workers=8
):
    """Upload every file in a list to a bucket, concurrently in a process pool.

    Each blob name is derived from the filename, not including the
    `source_directory` parameter. For complete control of the blob name for each
    file (and other aspects of individual blob metadata), use
    transfer_manager.upload_many() instead.
    """

    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # A list (or other iterable) of filenames to upload.
    # filenames = ["file_1.txt", "file_2.txt"]

    # The directory on your computer that is the root of all of the files in the
    # list of filenames. This string is prepended (with os.path.join()) to each
    # filename to get the full path to the file. Relative paths and absolute
    # paths are both accepted. This string is not included in the name of the
    # uploaded blob; it is only used to find the source files. An empty string
    # means "the current working directory". Note that this parameter allows
    # directory traversal (e.g. "/", "../") and is not intended for unsanitized
    # end user input.
    # source_directory=""

    # The maximum number of processes to use for the operation. The performance
    # impact of this value depends on the use case, but smaller files usually
    # benefit from a higher number of processes. Each additional process occupies
    # some CPU and memory resources until finished. Threads can be used instead
    # of processes by passing `worker_type=transfer_manager.THREAD`.
    # workers=8

    from google.cloud.storage import Client, transfer_manager

    storage_client = Client()
    bucket = storage_client.bucket(bucket_name)

    results = transfer_manager.upload_many_from_filenames(
        bucket, filenames, source_directory=source_directory, max_workers=workers
    )

    for name, result in zip(filenames, results):
        # The results list is either `None` or an exception for each filename in
        # the input list, in order.

        if isinstance(result, Exception):
            print("Failed to upload {} due to exception: {}".format(name, result))
        else:
            print("Uploaded {} to {}.".format(name, bucket.name))

En el siguiente ejemplo, se suben todos los objetos con un prefijo común de forma simultánea:

def upload_directory_with_transfer_manager(bucket_name, source_directory, workers=8):
    """Upload every file in a directory, including all files in subdirectories.

    Each blob name is derived from the filename, not including the `directory`
    parameter itself. For complete control of the blob name for each file (and
    other aspects of individual blob metadata), use
    transfer_manager.upload_many() instead.
    """

    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"

    # The directory on your computer to upload. Files in the directory and its
    # subdirectories will be uploaded. An empty string means "the current
    # working directory".
    # source_directory=""

    # The maximum number of processes to use for the operation. The performance
    # impact of this value depends on the use case, but smaller files usually
    # benefit from a higher number of processes. Each additional process occupies
    # some CPU and memory resources until finished. Threads can be used instead
    # of processes by passing `worker_type=transfer_manager.THREAD`.
    # workers=8

    from pathlib import Path

    from google.cloud.storage import Client, transfer_manager

    storage_client = Client()
    bucket = storage_client.bucket(bucket_name)

    # Generate a list of paths (in string form) relative to the `directory`.
    # This can be done in a single list comprehension, but is expanded into
    # multiple lines here for clarity.

    # First, recursively get all files in `directory` as Path objects.
    directory_as_path_obj = Path(source_directory)
    paths = directory_as_path_obj.rglob("*")

    # Filter so the list only includes files, not directories themselves.
    file_paths = [path for path in paths if path.is_file()]

    # These paths are relative to the current working directory. Next, make them
    # relative to `directory`
    relative_paths = [path.relative_to(source_directory) for path in file_paths]

    # Finally, convert them all to strings.
    string_paths = [str(path) for path in relative_paths]

    print("Found {} files.".format(len(string_paths)))

    # Start the upload.
    results = transfer_manager.upload_many_from_filenames(
        bucket, string_paths, source_directory=source_directory, max_workers=workers
    )

    for name, result in zip(string_paths, results):
        # The results list is either `None` or an exception for each filename in
        # the input list, in order.

        if isinstance(result, Exception):
            print("Failed to upload {} due to exception: {}".format(name, result))
        else:
            print("Uploaded {} to {}.".format(name, bucket.name))

Ruby

Si deseas obtener más información, consulta la documentación de referencia de la API de Cloud Storage Ruby.

Para autenticarte en Cloud Storage, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

def upload_file bucket_name:, local_file_path:, file_name: nil
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The path to your file to upload
  # local_file_path = "/local/path/to/file.txt"

  # The ID of your GCS object
  # file_name = "your-file-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name, skip_lookup: true

  file = bucket.create_file local_file_path, file_name

  puts "Uploaded #{local_file_path} as #{file.name} in bucket #{bucket_name}"
end

Terraform

Puedes usar un recurso de Terraform para subir un objeto. Se debe especificar content o source.

# Create a text object in Cloud Storage
resource "google_storage_bucket_object" "default" {
  name = "new-object"
  # Use `source` or `content`
  # source       = "/path/to/an/object"
  content      = "Data as string to be uploaded"
  content_type = "text/plain"
  bucket       = google_storage_bucket.static.id
}

API de REST

API de JSON

La API de JSON distingue entre las cargas de contenido multimedia, en las que solo se incluyen datos de objetos en la solicitud, y las cargas de varias partes de la API de JSON, en las que los datos de objeto y los metadatos de objeto se incluyen en la solicitud.

Carga de contenido multimedia (carga de una sola solicitud sin metadatos de objeto)

  1. Obtén un token de autorización de acceso de OAuth 2.0 Playground. Configura Playground para usar tus credenciales de OAuth. Para obtener instrucciones, consulta Autenticación de la API.
  2. Usa cURL para llamar a la API de JSON con una solicitud de objeto POST:

    curl -X POST --data-binary @OBJECT_LOCATION \
        -H "Authorization: Bearer OAUTH2_TOKEN" \
        -H "Content-Type: OBJECT_CONTENT_TYPE" \
        "https://storage.googleapis.com/upload/storage/v1/b/BUCKET_NAME/o?uploadType=media&name=OBJECT_NAME"

    Donde:

    • OBJECT_LOCATION es la ruta de acceso local a tu objeto. Por ejemplo, Desktop/dog.png.
    • OAUTH2_TOKEN es el token de acceso que generaste en el paso 1.
    • OBJECT_CONTENT_TYPE es el tipo de contenido del objeto. Por ejemplo, image/png.
    • BUCKET_NAME es el nombre del bucket al que subes el objeto. Por ejemplo, my-bucket.
    • OBJECT_NAME es el nombre codificado en URL que deseas darle a tu objeto. Por ejemplo, pets/dog.png, codificado en URL como pets%2Fdog.png.

Carga de varias partes de la API de JSON (carga de una sola solicitud que incluye metadatos de objeto)

  1. Obtén un token de autorización de acceso de OAuth 2.0 Playground. Configura Playground para usar tus credenciales de OAuth. Para obtener instrucciones, consulta Autenticación de la API.
  2. Crea un archivo multipart/related que contenga la siguiente información:

    --BOUNDARY_STRING
    Content-Type: application/json; charset=UTF-8
    
    OBJECT_METADATA
    
    --BOUNDARY_STRING
    Content-Type: OBJECT_CONTENT_TYPE
    
    OBJECT_DATA
    --BOUNDARY_STRING--

    Donde:

    • BOUNDARY_STRING es una string que defines para identificar las diferentes partes del archivo de varias partes. Por ejemplo, separator_string.
    • OBJECT_METADATA son metadatos que deseas incluir para el archivo, en formato JSON. Como mínimo, esta sección debe incluir un atributo name para el objeto, por ejemplo {"name": "myObject"}.
    • OBJECT_CONTENT_TYPE es el tipo de contenido del objeto. Por ejemplo, text/plain.
    • OBJECT_DATA son los datos del objeto.

    Por ejemplo:

    --separator_string
    Content-Type: application/json; charset=UTF-8
    
    {"name":"my-document.txt"}
    
    --separator_string
    Content-Type: text/plain
    
    This is a text file.
    --separator_string--
  3. Usa cURL para llamar a la API de JSON con una solicitud de objeto POST:

    curl -X POST --data-binary @MULTIPART_FILE_LOCATION \
        -H "Authorization: Bearer OAUTH2_TOKEN" \
        -H "Content-Type: multipart/related; boundary=BOUNDARY_STRING" \
        -H "Content-Length: MULTIPART_FILE_SIZE" \
        "https://storage.googleapis.com/upload/storage/v1/b/BUCKET_NAME/o?uploadType=multipart"

    Donde:

    • MULTIPART_FILE_LOCATION es la ruta local al archivo multiparte que creaste en el paso 2. Por ejemplo, Desktop/my-upload.multipart.
    • OAUTH2_TOKEN es el token de acceso que generaste en el paso 1.
    • BOUNDARY_STRING es la string de límite que definiste en el paso 2. Por ejemplo, my-boundary.
    • MULTIPART_FILE_SIZE es el tamaño total, en bytes, del archivo de varias partes que creaste en el paso 2. Por ejemplo, 2000000.
    • BUCKET_NAME es el nombre del bucket al que subes el objeto. Por ejemplo, my-bucket.

Si la solicitud se realiza correctamente, el servidor muestra el código de estado HTTP 200 OK junto con los metadatos del archivo.

API de XML

  1. Obtén un token de autorización de acceso de OAuth 2.0 Playground. Configura Playground para usar tus credenciales de OAuth. Para obtener instrucciones, consulta Autenticación de la API.
  2. Usa cURL para llamar a la API de XML con una solicitud de objeto PUT:

    curl -X PUT --data-binary @OBJECT_LOCATION \
        -H "Authorization: Bearer OAUTH2_TOKEN" \
        -H "Content-Type: OBJECT_CONTENT_TYPE" \
        "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    Donde:

    • OBJECT_LOCATION es la ruta de acceso local a tu objeto. Por ejemplo, Desktop/dog.png.
    • OAUTH2_TOKEN es el token de acceso que generaste en el paso 1.
    • OBJECT_CONTENT_TYPE es el tipo de contenido del objeto. Por ejemplo, image/png.
    • BUCKET_NAME es el nombre del bucket al que subes el objeto. Por ejemplo, my-bucket.
    • OBJECT_NAME es el nombre codificado en URL que deseas darle a tu objeto. Por ejemplo, pets/dog.png, codificado en URL como pets%2Fdog.png.

Puedes configurar metadatos de objeto adicionales como parte de la carga del objeto en los encabezados de la solicitud, de la misma manera que el ejemplo anterior configura Content-Type. Cuando trabajas con la API de XML, los metadatos solo pueden configurarse en el momento en que se escribe el objeto, como cuando se lo sube, copia o reemplaza. Para obtener más información, consulta Edita los metadatos de objetos.

¿Qué sigue?

Pruébalo tú mismo

Si es la primera vez que usas Google Cloud, crea una cuenta para evaluar el rendimiento de Cloud Storage en situaciones reales. Los clientes nuevos también obtienen $300 en créditos gratuitos para ejecutar, probar y, además, implementar cargas de trabajo.

Probar Cloud Storage gratis