利用flask-wtf验证上传的文件
定义验证表单类的时候,对文件类型的字段,需要采用FileField这个类型,即wtforms.FileField。 验证器需要从flask_wtf.file中导入。flask_wtf.file.FileRequired和flask_wtf.file.FileAllowed flask_wtf.file.FileRequired是用来验证文件上传不能为空。 flask_wtf.file.FileAllowed用来验证上传的文件的后缀名, 如常见图片后缀.jpg和.png以及.gif等。 在视图函数中,需要使用from werkzeug.datastructures import CombinedMultiDict来把request.form与request.files来进行合并。 最后使用 表单验证对象.validate()进行验证。upload.html文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传文件</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <table> <tr> <td>头像:</td> <td><input type="file" name="pichead"></td> </tr> <tr> <td>描述:</td> <td><input type="text" name="desc"></td> </tr> <tr> <td></td> <td><input type="submit" value="提交"></td> </tr> </table> </form> </body> </html>
formscheck.py文件:
from wtforms import Form,FileField,StringField from wtforms.validators import InputRequiredfrom flask_wtf.file import FileRequired,FileAllowed class UploadForm(Form): pichead = FileField(validators=[FileRequired(),FileAllowed(['jpg','png','gif'])]) desc = StringField(validators=[InputRequired()])
python启动文件:
from flask import Flask,request,render_template import os from werkzeug.utils import secure_filename from formscheck import UploadForm from werkzeug.datastructures import CombinedMultiDict app = Flask(__name__) UPLOAD_PATH = os.path.join(os.path.dirname(__file__),'images') #利用flask-wtf验证上传的文件 @app.route('/upload/',methods=['GET','POST']) def upload(): if request.method == 'GET': return render_template('upload.html') else: form = UploadForm(CombinedMultiDict([request.form,request.files])) if form.validate(): # desc = request.form.get("desc") # pichead = request.files.get("pichead") desc = form.desc.data pichead = form.pichead.data filename = secure_filename(pichead.filename) pichead.save(os.path.join(UPLOAD_PATH,filename)) print(desc) return '文件上传成功' else: print(form.errors) return "文件上传失败" if __name__ == '__main__': app.run(debug=True)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网之家。
新闻热点
疑难解答