美文网首页
FLASK文件上传 --- 使用flask_uploads +

FLASK文件上传 --- 使用flask_uploads +

作者: MoonMonsterss | 来源:发表于2018-10-21 19:01 被阅读155次
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    from flask import Blueprint, render_template
    from flask_uploads import UploadSet, IMAGES
    from flask_wtf import FlaskForm
    from flask_wtf.file import FileRequired, FileField, FileAllowed
    from wtforms import SubmitField
    
    bp = Blueprint('upload3', __name__, url_prefix='/upload3')
    photos = UploadSet('photos', IMAGES)
    
    
    class UploadFileForm(FlaskForm):
        photo = FileField(validators=[
            # 显示文件上传类型
            FileAllowed(photos, '只能上传图片'),
            # 必须上传文件
            FileRequired('没有选择文件')
        ])
        submit = SubmitField('上传')
    
    
    # 需要设置methods,前面忘记写了报错 
    @bp.route('/', methods=['GET', 'POST'])
    def index():
        # 不能传入request.form参数
        form = UploadFileForm()
        if form.validate_on_submit():
            # 从from对象中保存文件
            filename = photos.save(form.photo.data)
            # 还是返回了文件的url路径,而不是文件路径
            file_url = photos.url(filename)
        else:
            file_url = None
        return render_template('update3/index.html', form=form, file_url=file_url)
    





    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>UploadFile3</title>
    </head>
    <body>
    <form method="POST" enctype="multipart/form-data" action="{{ url_for('upload3.index') }}">
        {{ form.hidden_tag() }}
        {{ form.photo }}
        <input type="submit" value="提交">
        {% for error in form.photo.errors %}
            <span style="color:red;">{{ error }}</span>
        {% endfor %}
    </form>
    {% if file_url %}
        <br/>
        <img src="{{ file_url }}">
    {% endif %}
    </body>
    </html>
    



    因为用到了flask_uploads,所以还是需要加上两个函数

    configure_uploads(_app, photos)
    patch_request_class(_app)
    





    如果用上form表单的话,需要加上SECRET_KEY
    这个是随便写的,但正常情况下,肯定会生成随机的字符串。

    SECRET_KEY = 'abcdefg'
    

    相关文章

      网友评论

          本文标题:FLASK文件上传 --- 使用flask_uploads +

          本文链接:https://www.haomeiwen.com/subject/jctizftx.html