首页 > 解决方案 > 将文件返回到客户端而不保存在从 GCP 云存储下载的服务器端

问题描述

我正在处理 Flask 和 React 开发任务,因此我需要从 Flask 后端提供文件以响应客户端,该客户端是从 Flask 后端的 GCP 云存储下载的。

所以我目前的方法如下。

@app.route('/api/download-file', methods=['GET'])
@token_required
def download_blob():
    """Downloads a blob."""

    file_name = request.args.get('file_name')
    storage_client = storage.Client()

    bucket = storage_client.bucket(app.config.get('CLOUD_STORAGE_BUCKET'))
    blob = bucket.blob(file_name)
    print(blob.exists())
    blob.download_to_filename(file_name)
    return send_file("./" + file_name, as_attachment=True, mimetype="application/vnd.ms-excel")
    

所以我的问题是现在从烧瓶下载的所有文件都保存在服务器文件夹中,并且在返回语句之后,我无法执行删除该文件的行。

如果不保存在服务器内部,我找不到返回文件的任何解决方案

标签: pythonflaskgoogle-cloud-platformgoogle-cloud-storage

解决方案


基于 JohnHanley 的评论,可以使用以下代码实现目标。从这种方式可以提供任何文件而不用担心内容类型

@app.route('/api/download-file', methods=['GET'])
@token_required
def download_blob():
    """Downloads a blob."""

    file_name = "dir/" + request.args.get('file_name')
    storage_client = storage.Client()

    bucket = storage_client.bucket(app.config.get('CLOUD_STORAGE_BUCKET'))
    blob = bucket.get_blob(file_name)
    content_type = None
    try:
        content_type = blob.content_type
    except:
        pass
    file = blob.download_as_string()
    print(type(file), "downloaded type")
    return Response(file,  mimetype=content_type)

推荐阅读