【问题标题】:How to upload a file to GCS bucket using java如何使用 java 将文件上传到 GCS 存储桶
【发布时间】:2022-11-04 18:26:27
【问题描述】:
I am new to GCP and I want to upload a pem file to a particular bucket using java sdk. I followed the below code.
Storage storage = StorageOptions.getDefaultInstance().getService();
// Create a bucket
String bucketName = "my_unique_bucket"; // Change this to something unique
Bucket bucket = storage.create(BucketInfo.of(bucketName));
// Upload a blob to the newly created bucket
BlobId blobId = BlobId.of(bucketName, "my_blob_name");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "a simple blob".getBytes(UTF_8));
但是当我尝试通过邮递员进行测试时,我收到 415 不支持的媒体类型错误。
Can any one help me with this.
Thanks in advance
【问题讨论】:
标签:
java
google-cloud-platform
gcs
【解决方案1】:
从 Java 中使用 Google Cloud Storage 的推荐方法是使用 Cloud Storage Client Libraries。
下面的示例代码作为如何使用客户端库将对象上传到 Google Cloud Storage 的示例:
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
// You need to Create your service object :
Storage storage = StorageOptions.getDefaultInstance().getService();
// You need Create a bucket :
String bucketName = "my_unique_bucket"; // Change this to something unique
Bucket bucket = storage.create(BucketInfo.of(bucketName));
// Upload a blob to the newly created bucket
BlobId blobId = BlobId.of(bucketName, "my_blob_name");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "a simple blob".getBytes(UTF_8));
有关更多信息,请参阅此 SO 链接。