【问题标题】:Files are not getting downloaded with actual name Flask and Google cloud Storage未使用实际名称 Flask 和 Google 云存储下载文件
【发布时间】:2021-04-08 18:06:26
【问题描述】:

我正在构建一个烧瓶应用程序,该应用程序具有从谷歌云存储上传和下载文件的功能。对于下载部分,我已经实现了以下代码。

def downloadBlob(filename):
    storage_client = storage.Client(project=local_constants.PROJECT_NAME) # my project name here
    bucket = storage_client.bucket(local_constants.PROJECT_STORAGE_BUCKET) # bucket here
    blob = bucket.blob(filename)
    return blob.download_as_bytes()

我正在使用这段代码调用这个函数。

return Response(downloadBlob(cur_user['root_directory']+cur_dir+file_name), mimetype='application/octet-stream')

其中cur_user['root_directory']是一个63位随机数,每个用户都不同,cur_dir是63位随机数后的文件路径,file_name是用户选择下载的文件。

路径示例为4223099317976595278/test.txt。这意味着4223099317976595278 是用户的根目录,/ 是 cur_dir,text.txt 是文件名。

我面临的问题是我的文件自动重命名为download_file。我尝试将函数blob.download_as_bytes() 更改为blob.download_to_filename(),但它也对我不起作用。

如果文件位于云存储的根目录中,则它们的名称正确,如果文件位于其他文件夹中,则会发生上述问题。

谁能指出错误或建议我解决这个问题?

【问题讨论】:

  • 行为正常。所以,你需要更新你的代码。你能指望什么?哪个文件名?您能否再分享一点,以便轻松重现您的案例并帮助我们更轻松地为您提供帮助?
  • @guillaumeblaquiere 假设文件名为“test.txt”。下载时必须命名为“test.txt”而不是download_file。

标签: flask google-cloud-storage


【解决方案1】:

感谢@guillaume blaquire 提供答案,我进一步搜索了该问题并获得了一些相关信息。

函数download_as_bytes()download_as_string() 尝试下载具有实际名称的文件。这两个功能都适用于云存储根目录中的文件。例如同一文件在云存储中不同位置的路径为:

  1. file.txt(文件在云存储的根目录下。
  2. some_folder/some_other_folder/file.txt(文件存在于内部目录中)

在情况1,文件名是file.txt,但在情况2,文件名是some_folder/some_other_folder/file.txt,当我们尝试下载情况1中的文件时,它会被命名。但在情况 2 中,文件名将更改为 download_file,因为 / 是文件名中的非法字符。

所以我们必须在下载文件时使用Content-Disposition 标头为我们的文件指定一个特定的名称。

结论是,而不是使用此代码:

return Response(downloadBlob(cur_user['root_directory']+cur_dir+file_name), mimetype='application/octet-stream')

我应该使用这个代码。

return Response(downloadBlob(cur_user['root_directory']+cur_dir+file_name), mimetype='application/octet-stream', headers={"Content-Disposition": "filename="+file_name})

【讨论】:

    【解决方案2】:

    您需要告诉浏览器您想要的文件名。为此,您需要添加一个名为 Content-Disposition 的标题(例如)

    return Response(downloadBlob(cur_user['root_directory']+cur_dir+file_name), mimetype='application/octet-stream', headers={"Content-Disposition": "filename="+file_name})
    

    【讨论】:

    • 谢谢,你救了我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 2010-12-10
    • 2017-08-21
    • 2018-03-29
    • 1970-01-01
    • 2020-04-25
    相关资源
    最近更新 更多