flask 下载文件
from flask import Flask, send_file, Response, send_from_directoryimport ioapp = Flask(__name__)def file_send(file_path):# 发送大文件可以该方法with open(file_path, 'rb') as f:while 1:data = f.read(20 * 1024 * 10
·
from flask import Flask, send_file, Response, send_from_directory
import io
app = Flask(__name__)
def file_send(file_path): # 发送大文件可以该方法
with open(file_path, 'rb') as f:
while 1:
data = f.read(20 * 1024 * 1024) # 每次读取20M
if not data:
break
yield data
@app.route("/download1")
def download1():
return send_file('test.xlsx', as_attachment=True, attachment_filename='test.xlsx') # 或使用下行代码
# return send_from_directory('./', 'test.xlsx', as_attachment=True)
@app.route("/download2")
def download2():
with open('test.xlsx', 'rb') as f:
stream = f.read()
response = Response(stream, content_type='application/octet-stream')
response.headers['Content-disposition'] = 'attachment; filename=test.xlsx'
return response
@app.route("/download3")
def download3():
file = io.BytesIO() # 本地没有文件,将内容写入内存发送
file.write("你好".encode('utf-8'))
file.seek(0)
return send_file(file, as_attachment=True, attachment_filename="hi.txt") # 用下面3行代码也可
# response = Response(file, content_type='application/octet-stream')
# response.headers['Content-disposition'] = 'attachment; filename=test.xlsx'
# return response
@app.route("/download4")
def download4():
file_name = "MEM3.mp4"
response = Response(file_send(file_name), content_type='application/octet-stream')
response.headers["Content-disposition"] = f'attachment; filename={file_name}'
return response
if __name__ == '__main__':
app.run()
更多推荐
已为社区贡献2条内容
所有评论(0)