如何从 Google Cloud Platform 存储下载文件
问题描述
我正在阅读谷歌云存储的 python 文档,并成功地创建了一个上传文件的方法,但是,我无法找到使用 blob 的 URL 下载文件的方法.我能够使用文件名下载文件,但这不切实际,因为用户可以上传同名文件.该 blob 是私有的.我可以访问 blob 的 URL,所以我想知道是否可以使用此链接下载文件.
I was reading the python documentation for google cloud storage and was successfully able to create a method that uploads files, however, I am not able to find a way to download files using a blob's URL. I was able to download the file using the filename, but that's not practical since the user could upload files with the same name. The blob is private. I have access to the blob's URL, so I was wondering if there is a way to download files using this link.
这是我完美运行的上传代码:
This is my upload code which works perfectly:
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 来判断:
This code downloads the file, but I could only figure it out with the blob name, not 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 下载文件有任何建议或想法吗?
Any suggestions or thoughts on how to download the file using the blob's media link URL?
解决方案
比如bucket example-storage-bucket
有文件folder/example.pdf
及其
For example, bucket example-storage-bucket
has file folder/example.pdf
and its
链接 URL 是 https://storage.cloud.google.com/example-storage-bucket/folder/example.pdf
和URI 是 gs://example-storage-bucket/folder/example.pdf
使用以下函数通过 GCS 链接 URL 下载 blob(如果您使用的是 Python 3.x):
Use below function to download blob using GCS link URL(if you are using 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))
相关文章