Return 从 GCP 云存储下载的文件到客户端而不保存在服务器端

Return File to client side without save in sever side which download from GCP cloud storage

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

所以我目前的方法如下。

@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")
    

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

我找不到 return 文件的任何解决方案,而不保存在服务器中

根据 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)