Python 官方文档:入门教程 => 点击学习
目录方式一方式二完整代码方式一 @app.route("/download1") def download(): # return send_file('test.exe',
@app.route("/download1")
def download():
# return send_file('test.exe', as_attachment=True)
return send_file('2.jpg')
# return send_file('1.mp3')
如果不加as_attachment参数,则会向浏览器发送文件,比如发送一张图片:
发送mp3
加上as_attachment参数,则会下载文件。
通过Response来实现
部分代码如下:
@app.route("/download2")
def download2():
file_name = "1.jpg"
#https://www.runoob.com/Http/http-content-type.html
response = Response(file_send(file_name), content_type='image/jpeg')
response.headers["Content-disposition"] = f'attachment; filename={file_name}'
return response
其中content-type要根据文件的具体类型来设置,具体参考如下常见的:
content-type(内容类型),一般是指网页中存在的 content-type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件,content-type 标头告诉客户端实际返回的内容的内容类型。
常见的媒体格式类型如下:
app.py
from flask import Flask,send_file,Response
from flask_cors import CORS
app = Flask(__name__)
CORS(app,resources={r"/*": {"origins": "*"}},supports_credentials=True)
@app.route("/download1")
def download():
# return send_file('test.exe', as_attachment=True)
# return send_file('2.jpg')
return send_file('1.mp3')
# filefold file
# return send_from_directory('./', 'test.exe', as_attachment=True)
# send big file
def file_send(file_path):
with open(file_path, 'rb') as f:
while 1:
data = f.read(20 * 1024 * 1024) # per 20M
if not data:
break
yield data
@app.route("/download2")
def download2():
file_name = "1.jpg"
response = Response(file_send(file_name), content_type='image/jpeg')
response.headers["Content-disposition"] = f'attachment; filename={file_name}'
return response
if __name__ == '__main__':
app.config['JSON_AS_ASCII'] = False
app.run(debug=True)
到此这篇关于Flask框架编写文件下载接口过程讲解的文章就介绍到这了,更多相关Flask文件下载内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Flask框架编写文件下载接口过程讲解
本文链接: https://www.lsjlt.com/news/176556.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0