我正在阅读谷歌云存储的 python 文档,并成功地创建了一个上传文件的方法,但是,我无法找到使用 blob 的 URL 下载文件的方法。我可以使用文件名下载文件,但这不切实际,因为用户可以上传同名文件。该 blob 是私有(private)的。我可以访问 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 下载文件的任何建议或想法?
最佳答案
例如,存储桶 example-storage-bucket
有文件folder/example.pdf
及其
链接地址 是 https://storage.cloud.google.com/example-storage-bucket/folder/example.pdf
和
网址 是 gs://example-storage-bucket/folder/example.pdf
使用以下函数使用 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))
关于python - 如何从 Google Cloud Platform 存储下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62745795/