如何从 Google Cloud Platform 存储下载文件 [英] How to download a file from Google Cloud Platform storage

查看:40
本文介绍了如何从 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

链接 URLhttps://storage.cloud.google.com/example-storage-bucket/folder/example.pdfURIgs://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))

这篇关于如何从 Google Cloud Platform 存储下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆