分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

falsk之文件上传

发布时间:2023-09-06 02:20责任编辑:顾先生关键词:文件上传

在使用flask定义路由完成文件上传时,定义upload视图函数

from flask import Flask, render_templatefrom werkzeug.utils import secure_filenameimport osapp = Flask(__name__)app.debug = Trueapp.secret_key = ‘helloworld!!‘@app.route(‘/‘)def hello_world(): ???return ‘Hello World!‘@app.route(‘/upload‘,methods=[‘GET‘,‘POST‘])def upload(): ???if request.method == ‘POST‘: ???????f = request.files[‘file‘] ???????base_path = os.path.abspath(os.path.dirname(__file__)) ???????upload_path = os.path.join(base_path,‘static\uploads‘) ???????f.save(upload_path,secure_filename(f.filename)) ???????return "文件上传成功!!" ???return render_template(‘upload.html‘)@app.errorhandler(404)def page_not_found(error): ???return render_template(‘404.html‘),404if __name__ == ‘__main__‘: ???app.run(debug=True)

upload.html前端页面的内容为

<!DOCTYPE html><html lang="en"><head> ???<meta charset="UTF-8"> ???<title>文件上传</title></head><body><h1>文件上传示例</h1><form action="" method="post" enctype="multipart/form-data"> ???<input type="file" name="file"> ???<input type="submit" value="上传"></form></body></html>

启动项目,用浏览器打开http://127.0.0.1:5000/upload页面,前端页面显示如图所示

选择要上传的文件

文件选择完毕后,点击上传,flask会抛出异常,提供没有权限

修改upload视图函数

@app.route(‘/upload‘,methods=[‘GET‘,‘POST‘])def upload(): ???if request.method == ‘POST‘: ???????f = request.files[‘file‘] ???????base_path = os.path.abspath(os.path.dirname(__file__)) ???????upload_path = os.path.join(base_path,‘static\uploads‘,secure_filename(f.filename)) ???????f.save(upload_path) ???????return "文件上传成功!!" ???return render_template(‘upload.html‘)

再次进行文件上传,选中文件后,点击上传按钮,可以看到

由此可以看出,文件已经成功上传,此时查看项目static/uploads目录,可以看到上传的图片已经保存在flask项目中了

由此可以在Flask项目中完成文件上传功能!!

falsk之文件上传

原文地址:https://www.cnblogs.com/sui776265233/p/9893551.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved