Flask/Werkzeug 如何将 HTTP 内容长度标头附加到文件下载 [英] Flask/Werkzeug how to attach HTTP content-length header to file download
问题描述
我使用的是使用 Python 的 Flask(基于 Werkzeug).
I am using Flask (based on Werkzeug) which uses Python.
用户可以下载文件,我使用的是send_from_directory
-function.
The user can download a file, I'm using the send_from_directory
-function.
但是在实际下载文件时,没有设置 HTTP 标头 content-length
.所以用户不知道下载的文件有多大.
However when actually downloading the file, the HTTP header content-length
is not set. So the user has no idea how big the file being downloaded is.
我可以在 Python 中使用 os.path.getsize(FILE_LOCATION)
来获取文件大小(以字节为单位),但找不到设置content-length
Flask 中的标头.
I can use os.path.getsize(FILE_LOCATION)
in Python to get the file size (in bytes), but cannot find a way to set the content-length
header in Flask.
有什么想法吗?
推荐答案
我相信你会做这样的事情(未经测试):
I believe you'd do something like this (untested):
from flask import Response
response = Response()
response.headers.add('content-length', str(os.path.getsize(FILE_LOCATION)))
参见:Werkzug 的 Headers 对象 和 Flask 的响应对象.
这篇关于Flask/Werkzeug 如何将 HTTP 内容长度标头附加到文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!