从表单将多张图片上传到Google存储空间

时间:2020-11-01 11:06:55

标签: python flask google-cloud-platform

我正在尝试将多张图片(在140图像之间,以及每张<800 kb之间)上传到名为shootings的存储桶中的Google Cloud Storage中。用户提交包含一个或多个png或jpeg enter code here图片的表单

<form action="{{url_for('picture_storage_upload')}}" method="post" enctype="multipart/form-data">
    <label class="labelOne" for="pics">Upload your pictures</label>
    <input type="file" name="uploaded_pictures" multiple="multiple" accept="image/x-png, image/jpeg"/>
    <input type="submit">
</form>

提交此表单后,这称为Flask POST方法,称为picture_storage_upload。此方法用于将图片发送到GCP存储。

@app.route('/picture_storage_upload', methods=['POST'])
def picture_storage_upload():
    try:   
        shootings_storage = Storage.Storage('credentials.json', 'shootings_fr')
        shootings_storage.push_from_string(shootings_storage, 'test_picture')
    except Exception as e:
        return str(e)

由于该表单返回了我的字节,因此我正在使用push_from_string中的Storage Class方法

class Storage:
    def __init__(self, credentials, bucket_name):
        self.storage_client = storage.Client.from_service_account_json(credentials)
        self.bucket_name = bucket_name
        self.bucket = None 
        
    def push(self, local_file_name, target_file_name):
        self.bucket = self.storage_client.get_bucket(self.bucket_name)
        blob = self.bucket.blob(target_file_name)
        with open(local_file_name, 'rb') as f:
            blob.upload_from_file(f)
            
    def push_from_string(self, local_file_name, target_file_name):
        self.bucket = self.storage_client.get_bucket(self.bucket_name)
        self.bucket.blob(target_file_name).upload_from_string(local_file_name)
        return self.bucket.blob(target_file_name).public_url

我仍然收到错误“ could not be converted to bytes

0 个答案:

没有答案