Carregue objetos a partir de um sistema de ficheiros

Esta página mostra como carregar objetos para o seu contentor do Cloud Storage a partir do sistema de ficheiros local. Um objeto carregado consiste nos dados que quer armazenar, juntamente com os metadados associados. Para uma vista geral conceptual, incluindo como escolher o método de carregamento ideal com base no tamanho do ficheiro, consulte o artigo Carregamentos e transferências.

Para obter instruções sobre o carregamento a partir da memória, consulte o artigo Carregue objetos a partir da memória.

Funções necessárias

Para receber as autorizações necessárias para carregar objetos para um contentor, peça ao seu administrador para lhe conceder a função de IAM de utilizador de objetos de armazenamento (roles/storage.objectUser) no contentor. Esta função predefinida contém as autorizações necessárias para carregar um objeto para um contentor. Para ver as autorizações exatas necessárias, expanda a secção Autorizações necessárias:

Autorizações necessárias

  • storage.objects.create
  • storage.objects.delete
    • Esta autorização só é necessária para carregamentos que substituam um objeto existente.
  • storage.objects.get
    • Esta autorização só é necessária se planear usar a CLI Google Cloud para realizar as tarefas nesta página.
  • storage.objects.list
    • Esta autorização só é necessária se planear usar a CLI Google Cloud para realizar as tarefas nesta página. Esta autorização também é necessária se quiser usar a consola Google Cloud para validar os objetos que carregou.

Se planeia usar a Google Cloud consola para realizar as tarefas nesta página, também precisa da autorização storage.buckets.list, que não está incluída na função de utilizador do objeto de armazenamento (roles/storage.objectUser). Para receber esta autorização, peça ao seu administrador para lhe conceder a função de administrador do armazenamento (roles/storage.admin) no projeto.

Também pode obter estas autorizações com outras funções predefinidas ou funções personalizadas.

Para ver informações sobre a concessão de funções em contentores, consulte o artigo Use o IAM com contentores.

Carregue um objeto para um contentor

Conclua os passos seguintes para carregar um objeto para um contentor:

Consola

  1. Na Google Cloud consola, aceda à página Recipientes do Cloud Storage.

    Aceda a Recipientes

  2. Na lista de contentores, clique no nome do contentor para o qual quer carregar um objeto.

  3. No separador Objetos do contentor, pode:

    • Arraste ficheiros do ambiente de trabalho ou do gestor de ficheiros para o painel principal na consola Google Cloud .

    • Clique em Carregar > Carregar ficheiros, selecione os ficheiros que quer carregar na caixa de diálogo apresentada e, de seguida, clique em Abrir.

Para saber como obter informações detalhadas sobre erros relativos a operações do Cloud Storage falhadas na Google Cloud consola, consulte a secção Resolução de problemas.

Linha de comandos

Use o comando gcloud storage cp:

gcloud storage cp OBJECT_LOCATION gs://DESTINATION_BUCKET_NAME

Onde:

  • OBJECT_LOCATION é o caminho local para o seu objeto. Por exemplo, Desktop/dog.png.

  • DESTINATION_BUCKET_NAME é o nome do contentor para o qual está a carregar o seu objeto. Por exemplo, my-bucket.

Se for bem-sucedido, a resposta é semelhante ao exemplo seguinte:

Completed files 1/1 | 164.3kiB/164.3kiB

Pode definir metadados de objetos de chave fixa e personalizados como parte do carregamento de objetos através de comandos de flags.

Bibliotecas cliente

C++

Para mais informações, consulte a documentação de referência da API C++ do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

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#

Para mais informações, consulte a documentação de referência da API C# do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.


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

Para mais informações, consulte a documentação de referência da API Go do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

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

Para mais informações, consulte a documentação de referência da API Java do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte carrega um objeto individual:


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

O exemplo seguinte carrega vários objetos em simultâneo:

import com.google.cloud.storage.transfermanager.ParallelUploadConfig;
import com.google.cloud.storage.transfermanager.TransferManager;
import com.google.cloud.storage.transfermanager.TransferManagerConfig;
import com.google.cloud.storage.transfermanager.UploadResult;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

class UploadMany {

  public static void uploadManyFiles(String bucketName, List<Path> files) throws IOException {
    TransferManager transferManager = TransferManagerConfig.newBuilder().build().getService();
    ParallelUploadConfig parallelUploadConfig =
        ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();
    List<UploadResult> results =
        transferManager.uploadFiles(files, parallelUploadConfig).getUploadResults();
    for (UploadResult result : results) {
      System.out.println(
          "Upload for "
              + result.getInput().getName()
              + " completed with status "
              + result.getStatus());
    }
  }
}

O exemplo seguinte carrega todos os objetos com um prefixo comum em simultâneo:

import com.google.cloud.storage.transfermanager.ParallelUploadConfig;
import com.google.cloud.storage.transfermanager.TransferManager;
import com.google.cloud.storage.transfermanager.TransferManagerConfig;
import com.google.cloud.storage.transfermanager.UploadResult;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

class UploadDirectory {

  public static void uploadDirectoryContents(String bucketName, Path sourceDirectory)
      throws IOException {
    TransferManager transferManager = TransferManagerConfig.newBuilder().build().getService();
    ParallelUploadConfig parallelUploadConfig =
        ParallelUploadConfig.newBuilder().setBucketName(bucketName).build();

    // Create a list to store the file paths
    List<Path> filePaths = new ArrayList<>();
    // Get all files in the directory
    // try-with-resource to ensure pathStream is closed
    try (Stream<Path> pathStream = Files.walk(sourceDirectory)) {
      pathStream.filter(Files::isRegularFile).forEach(filePaths::add);
    }
    List<UploadResult> results =
        transferManager.uploadFiles(filePaths, parallelUploadConfig).getUploadResults();
    for (UploadResult result : results) {
      System.out.println(
          "Upload for "
              + result.getInput().getName()
              + " completed with status "
              + result.getStatus());
    }
  }
}

Node.js

Para mais informações, consulte a documentação de referência da API Node.js do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte carrega um 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);

O exemplo seguinte carrega vários objetos em simultâneo:

/**
 * 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 upload
// const firstFilePath = 'your-first-file-name';

// The ID of the second GCS file to upload
// 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);

O exemplo seguinte carrega todos os objetos com um prefixo comum em simultâneo:

/**
 * 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

Para mais informações, consulte a documentação de referência da API PHP do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

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

Para mais informações, consulte a documentação de referência da API Python do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

O exemplo seguinte carrega um 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}."
    )

O exemplo seguinte carrega vários objetos em simultâneo:

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))

O exemplo seguinte carrega todos os objetos com um prefixo comum em simultâneo:

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

Para mais informações, consulte a documentação de referência da API Ruby do Cloud Storage.

Para se autenticar no Cloud Storage, configure as Credenciais padrão da aplicação. Para mais informações, consulte o artigo Configure a autenticação para bibliotecas de cliente.

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

Pode usar um recurso do Terraform para carregar um objeto. Tem de especificar content ou 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
}

APIs REST

API JSON

A API JSON distingue entre carregamentos de multimédia, nos quais apenas os dados do objeto são incluídos no pedido, e carregamentos multipartes da API JSON, nos quais os dados do objeto e os metadados do objeto são incluídos no pedido.

Carregamento de multimédia (um carregamento de pedido único sem metadados de objetos)

  1. Ter a CLI gcloud instalada e inicializada, o que lhe permite gerar um token de acesso para o cabeçalho Authorization.

  2. Use cURL para chamar a API JSON com um pedido de POST objeto:

    curl -X POST --data-binary @OBJECT_LOCATION \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: OBJECT_CONTENT_TYPE" \
        "https://storage.googleapis.com/upload/storage/v1/b/BUCKET_NAME/o?uploadType=media&name=OBJECT_NAME"

    Onde:

    • OBJECT_LOCATION é o caminho local para o seu objeto. Por exemplo, Desktop/dog.png.
    • OBJECT_CONTENT_TYPE é o tipo de conteúdo do objeto. Por exemplo, image/png.
    • BUCKET_NAME é o nome do contentor para o qual está a carregar o seu objeto. Por exemplo, my-bucket.
    • OBJECT_NAME é o nome codificado em URL que quer dar ao seu objeto. Por exemplo, pets/dog.png, URL codificado como pets%2Fdog.png.

Carregamento multipartes da API JSON (um carregamento de pedido único que inclui metadados de objetos)

  1. Ter a CLI gcloud instalada e inicializada, o que lhe permite gerar um token de acesso para o cabeçalho Authorization.

  2. Crie um ficheiro multipart/related que contenha as seguintes informações:

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

    Onde:

    • BOUNDARY_STRING é uma string que define e que identifica as diferentes partes do ficheiro multipartes. Por exemplo, separator_string.
    • OBJECT_METADATA são metadados que quer incluir para o ficheiro, no formato JSON. No mínimo, esta secção deve incluir um atributo name para o objeto, por exemplo, {"name": "myObject"}.
    • OBJECT_CONTENT_TYPE é o tipo de conteúdo do objeto. Por exemplo, text/plain.
    • OBJECT_DATA são os dados do objeto.

    Por exemplo:

    --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. Use cURL para chamar a API JSON com um pedido de POST objeto:

    curl -X POST --data-binary @MULTIPART_FILE_LOCATION \
        -H "Authorization: Bearer $(gcloud auth print-access-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"

    Onde:

    • MULTIPART_FILE_LOCATION é o caminho local para o ficheiro multipartes que criou no passo 2. Por exemplo, Desktop/my-upload.multipart.
    • BOUNDARY_STRING é a string de limite que definiu no passo 2. Por exemplo, my-boundary.
    • MULTIPART_FILE_SIZE é o tamanho total, em bytes, do ficheiro multipartes que criou no passo 2. Por exemplo, 2000000.
    • BUCKET_NAME é o nome do contentor para o qual está a carregar o seu objeto. Por exemplo, my-bucket.

Se o pedido for bem-sucedido, o servidor devolve o código de estado HTTP 200 OK juntamente com os metadados do ficheiro.

API XML

  1. Ter a CLI gcloud instalada e inicializada, o que lhe permite gerar um token de acesso para o cabeçalho Authorization.

  2. Use cURL para chamar a API XML com um pedido de PUT objeto

    curl -X PUT --data-binary @OBJECT_LOCATION \
        -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        -H "Content-Type: OBJECT_CONTENT_TYPE" \
        "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    Onde:

    • OBJECT_LOCATION é o caminho local para o seu objeto. Por exemplo, Desktop/dog.png.
    • OBJECT_CONTENT_TYPE é o tipo de conteúdo do objeto. Por exemplo, image/png.
    • BUCKET_NAME é o nome do contentor para o qual está a carregar o seu objeto. Por exemplo, my-bucket.
    • OBJECT_NAME é o nome codificado em URL que quer dar ao seu objeto. Por exemplo, pets/dog.png, URL codificado como pets%2Fdog.png.

Pode definir metadados de objetos adicionais como parte do carregamento de objetos nos cabeçalhos do pedido da mesma forma que o exemplo anterior define Content-Type. Quando trabalha com a API XML, os metadados só podem ser definidos no momento em que o objeto é escrito, como quando carrega, copia ou substitui o objeto. Para mais informações, consulte o artigo Editar metadados de objetos.

Carregue o conteúdo de um diretório para um contentor

Conclua os passos seguintes para copiar o conteúdo de um diretório para um contentor:

Linha de comandos

Use o comando gcloud storage rsync com a flag --recursive:

gcloud storage rsync --recursive LOCAL_DIRECTORY gs://DESTINATION_BUCKET_NAME/FOLDER_NAME

Onde:

  • LOCAL_DIRECTORY é o caminho para o diretório que contém os ficheiros que quer carregar como objetos. Por exemplo, ~/my_directory.

  • DESTINATION_BUCKET_NAME é o nome do contentor para o qual quer carregar objetos. Por exemplo, my-bucket.

  • FOLDER_NAME (opcional) é o nome da pasta no contentor para o qual quer carregar objetos. Por exemplo, my-folder.

Se for bem-sucedido, a resposta é semelhante ao exemplo seguinte:

Completed files 1/1 | 5.6kiB/5.6kiB

Pode definir metadados de objetos de chave fixa e personalizados como parte do carregamento de objetos através de comandos de flags.

O que se segue?

Experimente

Se está a usar o Google Cloud pela primeira vez, crie uma conta para avaliar o desempenho do Cloud Storage em cenários reais. Os novos clientes também recebem 300 USD em créditos gratuitos para executar, testar e implementar cargas de trabalho.

Experimentar o Cloud Storage gratuitamente