当前位置: 移动技术网 > IT编程>脚本编程>Python > flask利用flask-wtf验证上传的文件的方法

flask利用flask-wtf验证上传的文件的方法

2020年03月09日  | 移动技术网IT编程  | 我要评论

健康之路糖尿病,识字八,九六中文网

利用flask-wtf验证上传的文件

  1. 定义验证表单类的时候,对文件类型的字段,需要采用filefield这个类型,即wtforms.filefield。
  2. 验证器需要从flask_wtf.file中导入。flask_wtf.file.filerequired和flask_wtf.file.fileallowed
  3. flask_wtf.file.filerequired是用来验证文件上传不能为空。
  4. flask_wtf.file.fileallowed用来验证上传的文件的后缀名, 如常见图片后缀.jpg和.png以及.gif等。
  5. 在视图函数中,需要使用from werkzeug.datastructures import combinedmultidict来把request.form与request.files来进行合并。
  6. 最后使用 表单验证对象.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 inputrequired
from 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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网