用Python将图像文件上传到Google Bucket

用Python将图像文件上传到Google Bucket,python,google-cloud-storage,Python,Google Cloud Storage,我正在尝试用Python创建一个函数,其中传递一个文件名和一个图像对象,我希望将其上传到Google存储桶。我已经创建了bucket,在一个环境变量中有了所有凭据,但是我对整个过程感到困惑 目前,我有以下设置: class ImageStorage: bucket_name = os.getenv('STORAGE_BUCKET_NAME') project_name = os.getenv('STORAGE_BUCKET_PROJECT_ID') client = s

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

目前,我有以下设置:

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.
我不确定如何提供此图像对象的字节大小。我是否首先需要从图像对象本地创建一个文件,然后再上传它

根据Github,您应该为流上传提供chunk_size参数

blob = self.bucket.blob(filename, chunk_size=262144) # 256KB
blob.upload_from_file(image)
int–每次迭代时数据块的大小(以字节为单位)。这必须是每个API规范256 KB的倍数