Flask 文件流下载
from flask import jsonify, json, request, make_response, Response, stream_with_context, send_file
import mimetypes,os
@api.route("/downloadFile/<path:filename>")
def downloadFile(filename):
#baseDir = os.path.abspath(os.path.dirname(__file__)).split('applications')[0]
#pathname = os.path.join(baseDir, "static/public/" + filename)
baseDir = os.path.join(os.getcwd(), "static")
pathname = os.path.join(baseDir, filename)
print pathname
def send_chunk(): # 流式读取
store_path = pathname
with open(store_path, 'rb') as target_file:
while True:
chunk = target_file.read(20 * 1024 * 1024) # 每次读取20M
if not chunk:
break
yield chunk
response = Response(send_chunk(), content_type='application/octet-stream')
response.headers['Content-Disposition'] = 'attachment; filename={}'.format(filename)
return response
@api.route("/downloadFile2/<path:filename>")
def downloadFile2(filename):
import os
baseDir = os.path.join(os.getcwd(), "static")
pathname = os.path.join(baseDir, filename)
f = open(pathname, "rb")
response = Response(f.readlines())
# response = make_response(f.read())
mime_type = mimetypes.guess_type(filename)[0]
response.headers['Content-Type'] = mime_type
response.headers['Content-Disposition'] = 'attachment; filename={}'.format(filename.encode().decode('latin-1'))
return response
Last updated