一、flask向前端提供下载文件的api
@charts.route('/files') @func_time def get_file(): """ http://127.0.0.1:5000/charts/files 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:如果指定了文件的媒体类型(文件类型),指定了文件路径将自动进行检测,否则将引发异常。 as_attachment:如果想要以附件的形式将文件发给客户端应设为True。经测试如果为True会被下载到本地。 attachment_filename:需要配合as_attachment=True使用,将下载的附件更改成我们指定的名字。 add_etags=True:设置为“false”以禁用附加etags。 :return: """ # 文件的目录 # file_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'statics') # return send_from_directory(file_dir, '孙.xls') # 发送文件夹下的文件 # 文件的绝对路径 # file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'statics', '孙.xls') # return send_file(file_path) # 直接发送文件名 return charts.send_static_file('孙.xls') # 发送静态文件
- 经使用发现,暂未找到可以指定下载文件的名称,默认都是已url路径为文件名进行下载,如本例,下载的文件会以
files.xls
下载,并不会以孙.xls
文件名下载 - 三种提供下载文件的api
send_from_directory
、send_file
、send_static_file
- 待解决问题
- 如果按文件的原始名称下载,或者指定名称下载?
1. 不成熟解决,就是用户将要下载下来的文件名传递过来,而项目中路由配置成允许传参的路径即`/files/<file_path>` @app.route("/download/<filepath>", methods=['GET']) def download_file(filepath): # 此处的filepath是文件的路径,但是文件必须存储在static文件夹下, 比如images\test.jpg return app.send_static_file(filepath)
二、make_response的使用
# 测试内置make_response方法的使用 @charts.route('/make_response') def test_response(): """ http://127.0.0.1:5000/charts/make_response :return: """ # 返回内容 # response = make_response('<h3>奋斗中,you can just try it!!!</h3>') # return response # 返回页面 # response = make_response(render_template('hello.html')) # return response # 返回页面同时返回指定的状态码 # response = make_response(render_template('hello.html'), 2000) # return response # 也可以直接返回状态码 response = make_response(render_template('hello.html')) return response, 2001