使用Flask-WTF验证文件


1、index.html

<form action="" method="post" enctype="multipart/form-data">
  <table>
    <tbody>
    <tr>
      <td>上传图片:</td>
      <td><input type="file" name="pic"></td>
    </tr>
    <tr>
      <td>图片名称:</td>
      <td><input type="text" name="picname"></td>
    </tr>
    <tr>
      <td></td>
      <td><input type="submit" value="立即提交"></td>
    </tr>
    </tbody>
  </table>
</form>
{% if picname %}
  {{ picname }} 上传成功
{% endif %}
{% for error in form.pic.errors %}
  <p>{{ error }}</p>
{% endfor %}
{% for error in form.picname.errors %}
  <p>{{ error }}</p>
{% endfor %}

2、app.py

from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
from wtforms import Form, StringField, FileField
from wtforms.validators import InputRequired
from flask_wtf.file import FileRequired, FileAllowed
from werkzeug.datastructures import CombinedMultiDict
import os

class UploadForm(Form):
    pic = FileField(validators=[
        FileRequired(message='未选择图片'),
        FileAllowed(['jpg', 'gif', 'png'], message='图片格式不正确')
    ])
    picname = StringField(validators=[
        InputRequired(message='图片名称不能为空')
    ])

app = Flask(__name__)

UPLOAD_PATH = os.path.join(os.path.dirname(__file__), 'static/uploads')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = UploadForm(CombinedMultiDict([request.form, request.files]))
    if request.method == 'GET':
        return render_template('index.html', form=form)
    else:
        if form.validate():
            pic = request.files.get('pic')
            picname = request.form.get('picname')
            filename = secure_filename(pic.filename)
            pic.save(os.path.join(UPLOAD_PATH, filename))
            return render_template('index.html', picname=picname, form=form)
        else:
            return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run()

results matching ""

    No results matching ""