有本地文件
放到nginx跟目录下,通过访问nginx下载:略
flask返回文件
@api.route('/file/down') def excel_down(): directory = r'D:/' filename = 'www.rar' file_name = '测试.rar' response = make_response(send_from_directory(directory, filename, as_attachment=True)) response.headers["Content-Disposition"] = "attachment; filename={}".format(file_name) return response
没有本地文件
通过设置response的类型下载
yield作用是后台生成一部分数据,前台下载一部分,不是等到全部传输完再进行下载,减少耗时
@api.route('/stream/down') def stream_down(): def generate(): for row in range(50000): line = [] for col in range(500): line.append(str(col)) if row % 1000 == 0: print 'row: %d' % row yield ','.join(line) + ' ' response = Response(generate(), mimetype='text/csv') response.headers["Content-Disposition"] = "attachment; filename={}".format('大文件.csv') return response
生成excel并下载
@api.route('/test3') def test3(): from openpyxl import Workbook wb = Workbook() ws = wb.active ws['A1'] = 42 ws['B1'] = "你 好" + "automation test" file_name = 'test.xlsx' wb.save(file_name) directory = '' response = make_response(send_from_directory(directory, file_name, as_attachment=True)) response.headers["Content-Disposition"] = "attachment; filename={}".format(file_name) return response
window.open(PreURL+'test3') //window.open写在链接中的参数后台用get方法就能取到
常用mimetype
-
text/html(默认的,html文件)
-
text/plain(纯文本)
-
text/css(css文件)
-
text/javascript(js文件)
-
application/x-www-form-urlencoded(普通的表单提交)
-
multipart/form-data(文件提交)
-
application/json(json传输)
-
application/xml(xml文件)