Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to update blob content in GCS?

I would like to write a file to GCS bucket, and if it exists just overwrite it.
The python docs show it's possible to overwrite the content of a blob using blob.upload_from_string('New contents!').

For Java I only found delete/create (update just updates the metadata).
So my code currently do this:

  public boolean doesObjectExist(String bucketName, String objectName) {
    Blob object = storage.get(bucketName, objectName);
    return object != null;
  }

  public void uploadObject(String bucketName, String objectName, String content) {
    BlobId blobId = BlobId.of(bucketName, objectName);
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
    if (doesObjectExist(bucketName, objectName)){
      storage.delete(bucketName, objectName);
    }
    storage.create(blobInfo, content.getBytes(UTF_8));
  }

Is there something overwrite via the Java API?

like image 680
oshai Avatar asked Sep 05 '25 00:09

oshai


1 Answers

You can't update the Blob content (even in Python!). You can only create, delete, read. You can't move, you can't rename. These 2 operations perform a create (with the new name/destination) and a delete (the old name).

So now, how you overwrite the existing content: simply write the content. If it exists, it will be replaced. If you have activated the versioning on the bucket, the previous version is kept as noncurrent version, and the uploaded content is served as live version.

like image 116
guillaume blaquiere Avatar answered Sep 07 '25 16:09

guillaume blaquiere