函数包含在 flask.helpers
文件中:
def send_file(
filename_or_fp,
mimetype=None,
as_attachment=False,
attachment_filename=None,
add_etags=True,
cache_timeout=None,
conditional=False,
last_modified=None,
):
...
参数:
- filename_or_fp: 是一个文件描述符或文件绝对路径或相对路径。
- mimetype:文件类型 string,可不填;
- as_attachment: bool, 是否在 header 中添加
Content-Disposition
字段,比如Content-Disposition: attachment; filename=anaconda3.tar.gz
,attachment
为以附件方式下载,filename
是下载时默认的文件名。 - attachment_filename: 下载时使用的文件名 string,若省略,则使用文件实际真实名称;
- add_etags:默认添加 etags,string;
- cache_timeout:缓存时间,单位秒,默认使用 config 中的
send_file_max_age_default
; - conditional:是否支持断点续传,bool;
- last_modified: 文件的最后修改时间,时间戳,不填的话使用文件实际真实的最后修改时间。
断点续传测试
首先查看响应头文件:
HTTP/1.0 200 OK
Content-Disposition: attachment; filename=anaconda3.tar.gz
Content-Length: 3166777919 # 整个文件的大小
Content-Type: application/x-tar
Last-Modified: Sat, 29 Sep 2018 03:58:14 GMT
Cache-Control: public, max-age=43200
Expires: Tue, 12 Nov 2019 19:38:55 GMT
ETag: "1538193494.33892-3166777919-2712605243" # 获取 Etag
Date: Tue, 12 Nov 2019 07:38:55 GMT
Accept-Ranges: bytes
Server: Werkzeug/0.16.0 Python/3.7.0
比如我想从 第 3166777500
字节开始下载(那么可下载的内容大小 为 3166777919
- 3166777500
= 419
):
那么请求需要携带 Range
字段和 If-Match
字段的 header
curl http://dev.example.com:5000/download -i --header "Range: bytes=3166777500-" --header "If-Match: '1538193494.33892-3166777919-2712605243'"
HTTP/1.0 206 PARTIAL CONTENT # 状态码 206
Content-Length: 419 # 内容大小正确
Content-Type: application/x-tar
Last-Modified: Sat, 29 Sep 2018 03:58:14 GMT
Cache-Control: public, max-age=43200
Expires: Tue, 12 Nov 2019 19:29:38 GMT
ETag: "1538193494.33892-3166777919-2712605243"
Date: Tue, 12 Nov 2019 07:29:38 GMT
Accept-Ranges: bytes
Content-Range: bytes 3166777500-3166777918/3166777919
Server: Werkzeug/0.16.0 Python/3.7.0
下载到文件:
curl http://dev.example.com:5000/download -i --header "Range: bytes=3166777500-" --header "If-Match: '1538193494.33892-3166777919-2712605243'" --output xxx.tar