akauppi
akauppi

Reputation: 18046

How to upload to Google Cloud Storage, with metadata, via the Java client?

It looks like the PHP client allows this: https://github.com/GoogleCloudPlatform/google-cloud-php/issues/626

On Java client (version 1.35.0), I haven't found the way to upload content and set its custom metadata, at one go.

Upvotes: 1

Views: 1694

Answers (2)

Slavkó Medvediev
Slavkó Medvediev

Reputation: 1571

Here's how it works in Java since at least version 1.35.0:

    public Blob uploadWithMetadata(Storage storage, Map<String, String> metadata, byte[] objectData) {
        BlobInfo blobInfo = BlobInfo
            .newBuilder("bucketName",  "objectName")
            .setMetadata(metadata)
            .build();
        return storage.create(blobInfo, objectData);
    }

As for client version 1.109.1, bucket API still does not allow to set custom metadata.

Upvotes: 0

akauppi
akauppi

Reputation: 18046

There are two ways to write to a bucket: via the bucket object, and (bypassing it) via the storage object.

The bucket API does not seem to allow providing metadata (blobs are identified simply by their name, as a string).

val sto: Storage = StorageOptions.getDefaultInstance.getService()
val bucket: Bucket = sto.get(bucketName)
bucket.create("abc", "ABC!".getBytes(UTF_8))

The storage API, in contrast, allows passing custom metadata:

val sto: Storage = StorageOptions.getDefaultInstance.getService()
val meta: Map[String,String] = Map("a" -> "42", "b" -> "25")

val bId: BlobId = BlobId.of(bucketName, "abc2")
val bInfo: BlobInfo = BlobInfo.newBuilder(bId)
  .setMetadata( meta.asJava )
  .build()

sto.create(bInfo, "ABC!".getBytes(UTF_8))

I hope this was clearer described somewhere in the documents, but maybe an entry in StackOverflow will suffice. :)

Upvotes: 2

Related Questions