從記憶體上傳物件

本頁面說明如何使用用戶端程式庫,將物件從記憶體上傳至 Cloud Storage 值區。如要避免從記憶體寫入本機檔案系統,上傳記憶體中的檔案就非常實用。

上傳的物件包含您要儲存的資料,以及任何相關聯的中繼資料。如需概念總覽,包括如何根據檔案大小選擇最佳上傳方法,請參閱「上傳和下載」。

必要的角色

如要取得從記憶體上傳物件至 bucket 的權限,請要求管理員授予 bucket 的 Storage 物件使用者 (roles/storage.objectUser) IAM 角色。這個預先定義的角色具備將物件上傳至值區所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

  • storage.objects.create
  • storage.objects.delete
    • 只有在上傳作業會覆寫現有物件時,才需要這項權限。

您也可以透過自訂角色取得這些權限。

如要瞭解如何授予值區角色,請參閱「搭配值區使用 IAM」。

從記憶體上傳物件

用戶端程式庫

C++

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

namespace gcs = ::google::cloud::storage; using ::google::cloud::StatusOr; [](gcs::Client client, std::string const& bucket_name,    std::string const& object_name) {   std::string const text = "Lorem ipsum dolor sit amet";   // For small uploads where the data is contiguous in memory use   // `InsertObject()`. For more specific size recommendations see   //     https://cloud.google.com/storage/docs/uploads-downloads#size   auto metadata = client.InsertObject(bucket_name, object_name, text);   if (!metadata) throw std::move(metadata).status();   std::cout << "Successfully wrote to object " << metadata->name()             << " its size is: " << metadata->size() << "\n";    // For larger uploads, or uploads where the data is not contiguous in   // memory, use `WriteObject()`. Consider using `std::ostream::write()` for   // best performance.   std::vector<std::string> v(100, text);   gcs::ObjectWriteStream stream =       client.WriteObject(bucket_name, object_name);   std::copy(v.begin(), v.end(), std::ostream_iterator<std::string>(stream));   stream.Close();    metadata = std::move(stream).metadata();   if (!metadata) throw std::move(metadata).status();   std::cout << "Successfully wrote to object " << metadata->name()             << " its size is: " << metadata->size()             << "\nFull metadata: " << *metadata << "\n"; }

C#

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

 using Google.Cloud.Storage.V1; using System; using System.IO; using System.Text;  public class UploadObjectFromMemorySample {     public void UploadObjectFromMemory(         string bucketName = "unique-bucket-name",         string objectName = "file-name",         string contents = "Hello world!")     {         var storage = StorageClient.Create();         byte[] byteArray = Encoding.UTF8.GetBytes(contents);         MemoryStream stream = new MemoryStream(byteArray);         storage.UploadObject(bucketName, objectName, "application/octet-stream" , stream);          Console.WriteLine($" {objectName} uploaded to bucket {bucketName} with contents: {contents}");     } } 

Go

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

import ( 	"bytes" 	"context" 	"fmt" 	"io" 	"time"  	"cloud.google.com/go/storage" )  // streamFileUpload uploads an object via a stream. func streamFileUpload(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()  	b := []byte("Hello world.") 	buf := bytes.NewBuffer(b)  	ctx, cancel := context.WithTimeout(ctx, time.Second*50) 	defer cancel()  	// Upload an object with storage.Writer. 	wc := client.Bucket(bucket).Object(object).NewWriter(ctx) 	wc.ChunkSize = 0 // note retries are not supported for chunk size 0.  	if _, err = io.Copy(wc, buf); err != nil { 		return fmt.Errorf("io.Copy: %w", err) 	} 	// Data can continue to be added to the file until the writer is closed. 	if err := wc.Close(); err != nil { 		return fmt.Errorf("Writer.Close: %w", err) 	} 	fmt.Fprintf(w, "%v uploaded to %v.\n", object, bucket)  	return nil } 

Java

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

 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.charset.StandardCharsets;  public class UploadObjectFromMemory {   public static void uploadObjectFromMemory(       String projectId, String bucketName, String objectName, String contents) 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 string of contents you wish to upload     // String contents = "Hello world!";      Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();     BlobId blobId = BlobId.of(bucketName, objectName);     BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();     byte[] content = contents.getBytes(StandardCharsets.UTF_8);      // Optional: set a generation-match precondition to enable automatic retries, avoid potential     // race     // conditions and data corruptions. The request returns a 412 error if the     // preconditions are not met.     Storage.BlobTargetOption 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.BlobTargetOption.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.BlobTargetOption.generationMatch(               storage.get(bucketName, objectName).getGeneration());     }     storage.create(blobInfo, content, precondition);      System.out.println(         "Object "             + objectName             + " uploaded to bucket "             + bucketName             + " with contents "             + contents);   } }

Node.js

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

/**  * TODO(developer): Uncomment the following lines before running the sample.  */ // The ID of your GCS bucket // const bucketName = 'your-unique-bucket-name';  // The contents that you want to upload // const contents = 'these are my contents';  // The new ID for your GCS file // const destFileName = 'your-new-file-name';  // Imports the Google Cloud Node.js client library const {Storage} = require('@google-cloud/storage');  // Creates a client const storage = new Storage();  async function uploadFromMemory() {   await storage.bucket(bucketName).file(destFileName).save(contents);    console.log(     `${destFileName} with contents ${contents} uploaded to ${bucketName}.`   ); }  uploadFromMemory().catch(console.error);

PHP

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

use Google\Cloud\Storage\StorageClient;  /**  * Upload an object from memory buffer.  *  * @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 $contents The contents to upload to the file.  *        (e.g. 'these are my contents')  */ function upload_object_from_memory(     string $bucketName,     string $objectName,     string $contents ): void {     $storage = new StorageClient();     if (!$stream = fopen('data://text/plain,' . $contents, 'r')) {         throw new \InvalidArgumentException('Unable to open file for reading');     }     $bucket = $storage->bucket($bucketName);     $bucket->upload($stream, [         'name' => $objectName,     ]);     printf('Uploaded %s to gs://%s/%s' . PHP_EOL, $contents, $bucketName, $objectName); }

Python

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

from google.cloud import storage   def upload_blob_from_memory(bucket_name, contents, destination_blob_name):     """Uploads a file to the bucket."""      # The ID of your GCS bucket     # bucket_name = "your-bucket-name"      # The contents to upload to the file     # contents = "these are my contents"      # 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)      blob.upload_from_string(contents)      print(         f"{destination_blob_name} with contents {contents} uploaded to {bucket_name}."     ) 

Ruby

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

如要驗證 Cloud Storage,請設定應用程式預設憑證。 詳情請參閱「設定用戶端程式庫的驗證機制」。

# The ID of your GCS bucket # bucket_name = "your-unique-bucket-name"  # The ID of your GCS object # file_name = "your-file-name"  # The contents to upload to your file # file_content = "Hello, world!"  require "google/cloud/storage"  storage = Google::Cloud::Storage.new bucket  = storage.bucket bucket_name, skip_lookup: true  file = bucket.create_file StringIO.new(file_content), file_name  puts "Uploaded file #{file.name} to bucket #{bucket_name} with content: #{file_content}"

後續步驟