![](/img/trans.png)
[英]How to download a file in Python or Linux from Google Cloud storage?
[英]How to download a file from Google Cloud Platform storage
我正在阅读谷歌云存储的 python 文档,并成功创建了一种上传文件的方法,但是,我无法找到使用 blob 的 URL 下载文件的方法。 我可以使用文件名下载文件,但这不切实际,因为用户可以上传同名文件。 该 blob 是私有的。 我可以访问 blob 的 URL,所以我想知道是否可以使用此链接下载文件。
这是我完美的上传代码:
def upload_blob(bucket_name, filename, file_obj):
if filename and file_obj:
storage_client = storage.Client()
bucket = storage_client.bucket('example-storage-bucket')
blob = bucket.blob(filename)
blob.upload_from_file(file_obj) # binary file data
form_logger.info('File {} uploaded'.format(filename))
return blob
此代码下载文件,但我只能用 blob 名称而不是 URL 找出它:
def download_blob(bucket_name, url):
if url:
storage_client = storage.Client()
bucket = storage_client.bucket('example-storage-bucket')
blob = bucket.blob(url)
blob.download_to_filename("example.pdf")
关于如何使用 blob 的媒体链接 URL 下载文件的任何建议或想法?
例如bucket example-storage-bucket
有文件folder/example.pdf
及其
Link URL is https://storage.cloud.google.com/example-storage-bucket/folder/example.pdf
and URI is gs://example-storage-bucket/folder/example.pdf
使用下面的 function 使用 GCS 链接 URL 下载 blob(如果您使用的是 Python 3.x):
import os
from urllib.parse import urlparse
def decode_gcs_url(url):
p = urlparse(url)
path = p.path[1:].split('/', 1)
bucket, file_path = path[0], path[1]
return bucket, file_path
def download_blob(url):
if url:
storage_client = storage.Client()
bucket, file_path = decode_gcs_url(url)
bucket = storage_client.bucket(bucket)
blob = bucket.blob(file_path)
blob.download_to_filename(os.path.basename(file_path))
我认为您的意思是您想将 blob 下载到名称基于 blob 名称的文件中,对吗? 如果是这样,您可以在 blob.metadata 中找到 blob 名称,然后根据该 blob 名称选择一个文件名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.