【问题标题】:Upload file to cloud storage from request without saving it locally从请求将文件上传到云存储而不在本地保存
【发布时间】:2022-01-04 01:39:54
【问题描述】:

我正在尝试使用我在 Flask (python) 上构建的 API 将文件上传到谷歌云存储,但我不想在本地保存文件。直接从请求中获取文件并上传到云存储。

上传到GCS方法

def upload_to_bucket(blob_name, path_to_file):
    """ Upload data to a bucket"""
    storage_client = storage.Client()

    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(blob_name)
    blob.upload_from_filename(path_to_file)

    #returns a public url
    return blob.public_url

从请求体中获取文件对象

file = request.files['file']

这就是我调用方法的方式

url = upload_to_bucket(file.name, file)

但在这里它返回 Attributer 错误。我尝试了 file.value、file.file 但这不起作用。

【问题讨论】:

标签: python flask file-upload python-requests google-cloud-storage


【解决方案1】:

使用 upload_from_string 方法。

file = request.files['file']
blob = bucket.blob(file.filename)
blob.upload_from_string(file.read(), content_type=file.content_type)

API Documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2019-04-12
    • 2022-11-15
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多