上傳物件

本頁介紹將物件上傳到 Cloud Storage 值區的選項。已上傳的物件包含您要儲存的資料以及任何相關聯的中繼資料。如需物件總覽,請參閱關鍵字詞物件命名需求

主控台

  1. 在 Google Cloud Platform Console 中開啟 Cloud Storage 瀏覽器。
    開啟 Cloud Storage 瀏覽器
  2. 在值區清單中找出您要將物件上傳到哪個值區,然後按一下該值區的名稱。

  3. 在值區的「物件」分頁中,從下列兩個方式擇一操作:

    • 將需要的檔案從桌面或檔案管理員拖曳到 GCP 主控台的主要窗格。

    • 按一下 [上傳檔案] 按鈕,在出現的對話方塊中選取您要上傳的檔案,然後按一下 [開啟]。

gsutil

使用 gsutil cp 指令:

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

其中:

  • [OBJECT_LOCATION] 是物件的本機路徑。例如 Desktop/dog.png

  • [DESTINATION_BUCKET_NAME] 是您要向其上傳物件的值區名稱。例如,my-bucket

如果成功,回應會類似以下範例:

Operation completed over 1 objects/58.8 KiB.

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

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

  if (!object_metadata) {
    throw std::runtime_error(object_metadata.status().message());
  }

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

C#

詳情請參閱 Cloud Storage C# API 參考說明文件

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

詳情請參閱 Cloud Storage Go API 參考說明文件

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

詳情請參閱 Cloud Storage Java API 參考說明文件

Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of("bucket", "blob_name");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

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

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

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';

// Uploads a local file to the bucket
await storage.bucket(bucketName).upload(filename, {
  // Support for HTTP requests made with `Accept-Encoding: gzip`
  gzip: true,
  // By setting the option `destination`, you can change the name of the
  // object you are uploading to a bucket.
  metadata: {
    // Enable long-lived HTTP caching headers
    // Use only if the contents of the file will never change
    // (If the contents will change, use cacheControl: 'no-cache')
    cacheControl: 'public, max-age=31536000',
  },
});

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

PHP

詳情請參閱 Cloud Storage PHP API 參考說明文件

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

詳情請參閱 Cloud Storage Python API 參考說明文件

使用 Blob.upload_from_file()Blob.upload_from_filename()Blob.upload_from_string() 方法來上傳物件。
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

詳情請參閱 Cloud Storage Ruby API 參考說明文件

# 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_id: project_id
bucket  = storage.bucket bucket_name

file = bucket.create_file local_file_path, storage_file_path

puts "Uploaded #{file.name}"

REST API

JSON API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 透過 POST 物件要求使用 cURL 呼叫 JSON API

    curl -X POST --data-binary @[OBJECT_LOCATION] \
    -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]"

    其中:

    • [OBJECT_LOCATION] 是物件的本機路徑。例如,Desktop/dog.png
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [OBJECT_CONTENT_TYPE] 是物件的內容類型。例如,image/png
    • [BUCKET_NAME] 是您要向其上傳物件的值區名稱。例如,my-bucket
    • [OBJECT_NAME] 是您要為物件命名的名稱。例如,pets/dog.png

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設為使用自己的 OAuth 憑證。
  2. 透過 PUT 物件要求使用 cURL 呼叫 XMLAPI

    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]"

    其中:

    • [OBJECT_LOCATION] 是物件的本機路徑。例如,Desktop/dog.png
    • [OAUTH2_TOKEN] 是您在步驟 1 產生的存取憑證。
    • [OBJECT_CONTENT_TYPE] 是物件的內容類型。例如,image/png
    • [BUCKET_NAME] 是您要向其上傳物件的值區名稱。例如,my-bucket
    • [OBJECT_NAME] 是您要為物件命名的名稱。例如,pets/dog.png

後續步驟

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Storage
需要協助嗎?請前往我們的支援網頁