[英]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.