Fifty-seven: flask of file uploads using the flask-wtf validate uploaded files

 

1, the installation: the install Flask-WTF PIP
2, define the form validation, field of the file, use: the FileField
. 3, the verifier imported from flask_wtf.file, FileRequired to verify documents must pass, FileAllowed to verify the file extensions
4, in view of the function, to the use werkzeug.datastructures.CombinedMultiDict request.files request.form and combined, and then passed verification 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 # verification document type 
from wtforms.validators Import InputRequired

from flask_wtf.file FileRequired # Import File verification will pass
from flask_wtf.file import FileAllowed # verification file extension


class UploadForm (Form1):
Avatar = the FileField (validators = [FileRequired ( 'file must pass'), FileAllowed ([' jpg ',' png ',' gif '], message =' file format error ')])
desc = StringField (validators = [InputRequired (' description information required ')])

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) # against hackers on the file name tricks: ../../ the User / XXX / .bashrc
avatar.save (the os.path.join ( 'Files', filename)) Save File #
Print (desc)
return 'file uploaded successfully'
the else:
return form.errors
return render_template ( 'upload.html')

 

Guess you like

Origin www.cnblogs.com/zhongyehai/p/11845927.html