五十七:flask文件上传之使用flask-wtf验证上传的文件

 

1、安装:pip install flask-wtf
2、定义表单验证的时候,对文件的字段,需使用:FileField
3、验证器从flask_wtf.file中导入,FileRequired为验证文件必传,FileAllowed为验证文件后缀名
4、在视图函数中,使用werkzeug.datastructures.CombinedMultiDict来把request.form和request.files合并,再传给form验证

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>上传文件</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<table>
<tbody>
<tr>
<td>头像:</td>
<td><input type="file" name="avatar"></td>
</tr>
<tr>
<td>描述:</td>
<td><input type="text" name="desc"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="点击提交"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>

from wtforms import Form, StringField, FileField  # 校验文件类型
from wtforms.validators import InputRequired

from flask_wtf.file import FileRequired # 验证文件必传
from flask_wtf.file import FileAllowed # 验证文件后缀名


class UploadForm(Form):
avatar = FileField(validators=[FileRequired('文件必传'), FileAllowed(['jpg', 'png', 'gif'], message='文件格式错误')])
desc = StringField(validators=[InputRequired('描述信息必填')])

import os
from flask import Flask, request, render_template, send_from_directory
from werkzeug.utils import secure_filename
from werkzeug.datastructures import CombinedMultiDict

from forms import UploadForm

app = Flask(__name__)


@app.route('/upload/', methods=['GET', 'POST'])
def upload():
form = UploadForm(CombinedMultiDict([request.form, request.files])) # 将文件与文字信息都传给form
if request.method == 'POST':
if form.validate():
desc = request.desc.data # == request.form.get('desc') # 获取描述信息
avatar = request.avatar.data # == request.files.get('avatar') # 获取文件:request.files
filename = secure_filename(avatar.filename) # 防黑客在文件名上做手脚:../../User/xxx/.bashrc
avatar.save(os.path.join('files', filename)) # 保存文件
print(desc)
return '文件上传成功'
else:
return form.errors
return render_template('upload.html')

 

posted @ 2019-11-12 22:38  向前走。  阅读(1402)  评论(0编辑  收藏  举报