python flask下载功能

前言

flask 下载功能


一、约定

要下载文件绝对路径:/tmp/flask_web/download/test.tar.gz
py主程序:/tmp/flask_web/main.py


二、main.py 内容

@app.route("/down/<path:filename>", methods=['GET', 'POST'])
def download_file(filename):
try:
# 需要知道2个参数, 第1个参数是本地目录的path, 第2个参数是文件名(带扩展名)
directory = os.getcwd() # 假设在当前目录
return send_from_directory(directory, filename, as_attachment=True)
except:
return '<h1>该文件不存在或无法下载</h1>'
if __name__ == '__main__':
app.run(host='0.0.0.0',port = 5000)

filename:需要发送的文件路径或者二进制文件对象
mimetype:文件的MIME类型,如果没有设置,会尝试根据文件名进行检测
as_attachment:布尔类型(默认False),为True表示下载保存文件,为False表示前端显示


三、运行 python 自带web服务,cesium

python3 main.py runserver 0.0.0.0:5000
python3 main.py runserver 192.168.1.11:5000

四、访问

http://192.168.1.1:5000/down/download/test.tar.gz

down 是绑定的路由
directory 获取到 main.py 所在路径 /tmp/flask_web
download 是你文件存放的路径,/tmp/flask_web/下的 download 文件夹



免责声明:本号所涉及内容仅供安全研究与教学使用,如出现其他风险,后果自负。




参考、来源:
https://blog.csdn.net/qq_44198436/article/details/106922355
https://blog.csdn.net/qq_42482078/article/details/131514743
https://blog.csdn.net/qq_45984664/article/details/128648899
https://blog.csdn.net/qq_40205116/article/details/110247395
https://geek-docs.com/flask/flask-questions/80_flask_flask_download_a_file.html
https://www.cnblogs.com/yuanfang0903/p/11446684.html
https://zhuanlan.zhihu.com/p/52198748 (显示文件夹下的文件列表)
https://www.cnblogs.com/kaerxifa/p/11780941.html



posted @   悟透  阅读(438)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2020-11-30 Etcd v3.1.15 在Linux CentOS7 集群配置 (单机改端口实现)
点击右上角即可分享
微信分享提示