How to upload a bytes image on Google Cloud Storage from a Python script

前端 未结 3 1425
清酒与你
清酒与你 2020-12-16 03:52

I want to upload an image on Google Cloud Storage from a python script. This is my code:

from oauth2client.service_account import ServiceAccountCredentials
f         


        
3条回答
  •  天命终不由人
    2020-12-16 04:38

    If you want to upload your image from file.

    import os
    from google.cloud import storage
    
    def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key):
        try:
            client = storage.Client()
            bucket = client.bucket(bucket_name)
            full_file_path = os.path.join(local_path, local_file_name)
            bucket.blob(target_key).upload_from_filename(full_file_path)
            return bucket.blob(target_key).public_url
    
        except Exception as e:
            print(e)
    
        return None
    

    but if you want to upload bytes directly:

    import os
    from google.cloud import storage
    
    def upload_data_to_gcs(bucket_name, data, target_key):
        try:
            client = storage.Client()
            bucket = client.bucket(bucket_name)
            bucket.blob(target_key).upload_from_string(data)
            return bucket.blob(target_key).public_url
    
        except Exception as e:
            print(e)
    
        return None
    

    note that target_key is prefix and the name of the uploaded file.

提交回复
热议问题