将文件上传到Google Cloud Storage(Java)

时间:2018-07-16 09:29:52

标签: java google-app-engine google-cloud-platform cloud google-cloud-storage

基本上,问题出在标题中:我不知道如何将文件上传到Google存储空间

我已经检查了此网页:
https://cloud.google.com/storage/docs/uploading-objects

在Java语言标签中,建议为“上载对象”使用以下两行:

InputStream content = new ByteArrayInputStream("Hello, World!".getBytes(UTF_8));
Blob blob = bucket.create(blobName, content, "text/plain");

可以从bucket对象接收上面的storage对象,这实际上是问题的根源

到目前为止,在我看过的所有教程中(特别是在本教程中:https://support.google.com/dfp_premium/answer/1733127?hl=en),storage属于com.google.api.services.storage.Storage而不是com.google.cloud.storage.Storage,并且实例化如下:

        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

        GoogleCredential credential = new GoogleCredential.Builder()
            .setTransport(httpTransport)
            .setJsonFactory(JacksonFactory.getDefaultInstance())
            .setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
            .setServiceAccountScopes(
                Collections.singleton(STORAGE_SCOPE))
            .setServiceAccountPrivateKeyFromP12File(p12File).build();

        storage = new com.google.api.services.storage.Storage.Builder(httpTransport,
            JacksonFactory.getDefaultInstance(), credential)
            .setApplicationName(PROJECT_NAME).build();

以这种方式创建存储对象后,我们可以获取存储桶对象,如下所示:

    com.google.api.services.storage.Storage.Buckets.Get object = storage.buckets().get(BUCKET_NAME);        
    com.google.api.services.storage.model.Bucket bucket = object.execute();

但是我不能使用com.google.api.services.storage.model.Bucket来上传文件,因为它没有上面提到的create()方法。我需要改用com.google.cloud.storage.Bucket

我也检查了这个stackoverflow问题:Upload image to Google Cloud Storage (Java)
并且提供的链接中的示例确实使用了com.google.cloud.storage.Storagecom.google.cloud.storage.Bucket,但它们从未像上面的代码一样显示如何传递凭证并实例化storage对象。

有人可以提供清晰,全面的Java代码片段来显示如何将文件上传到Google云端存储,包括storage对象的所有必要凭据实例化吗?

编辑。换句话说,我需要像上面一样自定义com.google.cloud.storage.Storage的实例化,而不是使用以下行:Storage storage = StorageOptions.getDefaultInstance().getService();

编辑2。最终,我现在可以通过以下代码检索存储桶后上传文件:

GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(KEY_JSN)).createScoped(Lists.newArrayList("https://www.googleapis.com/auth/devstorage.read_write"));

Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

Bucket bucket = storage.get(BUCKET_NAME);

我剩下的一个细微之处是以下几行:

Page<Bucket> buckets = storage.list();

返回一个空列表。能够通过get(bucket_name)接收特定的存储段meta的同时接收空的存储段列表是否有意义?

3 个答案:

答案 0 :(得分:1)

我能够使用documentation衍生的以下代码片段中的com.google.cloud.storage库创建并上传到存储桶:

public void createBlobFromByteArray(String blobName, String jsonPath, String bucketName) throws IOException {
                GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
                    .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
                Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
                Bucket bucket = storage.create(BucketInfo.of(bucketName));
                Blob blob = bucket.create(blobName, "Hello, World!".getBytes(UTF_8), "text/plain");
          }

您需要create a JSON service account key in and download it from the Google Cloud console。然后将其传递给GoogleCredentials方法以验证'storage'

答案 1 :(得分:0)

您是否找出原因? storage.list()返回项目中存储桶的列表。这对我来说可以。

EDIT#1: 您是否尝试使用Google API客户端库而不是Cloud Client库?

下面的示例代码:

     try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();

          // Authenticate using Google Application Default Credentials.
          GoogleCredential gCredential = GoogleCredential.getApplicationDefault();
          if (gCredential.createScopedRequired()) {
            List<String> scopes = new ArrayList<>();
            // Set Google Cloud Storage scope to Full Control.
            scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);
          }         

          // Create Storage object for listing buckets.
          Storage storage =
              new Storage.Builder(httpTransport, JSON_FACTORY, gCredential)
                  .setApplicationName(APPLICATION_NAME)
                  .build();     

        Buckets buckets = storage.buckets().list(projectId).execute(); <-- give your project identifier.
        for(Bucket buckt:buckets.getItems()) {
            System.out.println(buckt.getName());
        }

    } catch (GeneralSecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

如果您还没有尝试过,可以尝试一下,看看是否可行。如果没有,可以随身携带一些东西。如果可行,那么很可能我们的云客户端库中存在错误。

答案 2 :(得分:0)

  • 从命令行导出 Google 凭据 JSON:
export GOOGLE_APPLICATION_CREDENTIALS='\path\key.json'
  • 在应用程序中运行此代码:
Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of(BUCKET_NAME, OBJECT_NAME);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "Hello, World!".getBytes(UTF_8));