无法直接从URL将文件上传到Google Cloud
Storage。由于您是从本地环境运行脚本,因此要上载的文件内容必须在同一环境中。这意味着url的内容需要存储在内存中或文件中。
基于您的代码的示例展示了如何执行此操作:
选项1
:您可以使用该
wget模块,该模块将获取url并将其内容下载到本地文件中(类似于
wgetCLI命令)。请注意,这意味着文件将存储在本地,然后从文件上传。
os.remove上传完成后,我添加了一行以删除文件。
from google.cloud import storageimport wgetimport io, osproject_id = 'my-project'bucket_name = 'my-bucket'destination_blob_name = 'upload.test'storage_client = storage.Client.from_service_account_json('my_creds.json')source_file_name = 'http://www.hospiceofmontezuma.org/wp-content/uploads/2017/10/confused-man.jpg'def upload_blob(bucket_name, source_file_name, destination_blob_name): filename = wget.download(source_file_name) bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(filename, content_type='image/jpg') os.remove(filename)upload_blob(bucket_name, source_file_name, destination_blob_name)选项2
:使用该
urllib模块,其工作方式与该
wget模块相似,但不是写入文件,而是写入变量。请注意,我在Python3上做了这个示例,如果您打算在Python
2.X中运行脚本,则会有一些差异。
from google.cloud import storageimport urllib.requestproject_id = 'my-project'bucket_name = 'my-bucket'destination_blob_name = 'upload.test'storage_client = storage.Client.from_service_account_json('my_creds.json')source_file_name = 'http://www.hospiceofmontezuma.org/wp-content/uploads/2017/10/confused-man.jpg'def upload_blob(bucket_name, source_file_name, destination_blob_name): file = urllib.request.urlopen(source_file_name) bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_string(link.read(), content_type='image/jpg')upload_blob(bucket_name, source_file_name, destination_blob_name)


