在GCS中是否可以更新Blob内容?

huangapple go评论54阅读模式
英文:

Is it possible to update blob content in GCS?

问题

我想将文件写入GCS存储桶,如果文件已存在,就覆盖它。
Python文档显示可以使用blob.upload_from_string('新内容!')来覆盖blob的内容。

至于Java,我只找到了删除/创建(更新只会更新元数据)。
因此,我的代码目前执行以下操作:

  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));
  }

是否有类似通过Java API实现覆盖的方法呢?

英文:

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?

答案1

得分: 6

你无法更新 Blob 内容(即使在 Python 中也不行!)。你只能创建、删除、读取。你不能移动,也不能重命名。这两个操作会执行创建(使用新名称/目标)和删除(旧名称)。

那么现在,如何覆盖现有内容:只需写入该内容。如果它存在,它将被替换。如果你在存储桶上启用了版本控制,先前的版本将保留为非当前版本,上传的内容将作为活动版本提供。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月7日 18:59:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64242658.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定