【问题标题】:Uploading image file to Google Bucket in Python在 Python 中将图像文件上传到 Google 存储桶
【发布时间】:2019-12-06 09:49:40
【问题描述】:

我正在尝试在 Python 中创建一个函数,在该函数中我传递一个文件名和一个图像对象,我希望将其上传到 Google 存储桶。我已经创建了存储桶,我在环境变量中拥有所有凭据,但我对整个过程感到困惑。

目前我有以下设置:

class ImageStorage:
    bucket_name = os.getenv('STORAGE_BUCKET_NAME')
    project_name = os.getenv('STORAGE_BUCKET_PROJECT_ID')

    client = storage.Client(project=project_name)
    bucket = client.get_bucket(bucket_name)

    def save_image(self, filename, image):
        blob = self.bucket.blob(filename)
        blob.upload_from_file(image)

但是一旦我运行它,我就会得到错误:

total bytes could not be determined. Please pass an explicit size, or supply a chunk size for a streaming transfer.

我不确定如何提供此图像对象的字节大小。我是否首先需要从图像对象在本地创建一个文件,然后再上传它?

【问题讨论】:

    标签: python google-cloud-storage


    【解决方案1】:

    根据 Github issue,您应该提供 chunk_size 参数用于流上传。

    blob = self.bucket.blob(filename, chunk_size=262144) # 256KB
    blob.upload_from_file(image)
    

    chunk_size (int) – 每次迭代时数据块的大小(以字节为单位)。根据 API 规范,这必须是 256 KB 的倍数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 2015-09-27
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多