zoukankan      html  css  js  c++  java
  • 对文件上传使用表单验证

    from wtforms import Form,FileField,StringField
    from wtforms.validators import InputRequired
    from flask_wtf.file import FileRequired,FileAllowed
    
    
    class Upload(Form):
        avatar = FileField(validators=[FileRequired(),
                                       FileAllowed(['jpg','png','gif'])])#FileRequired文件必须要上传,
        # FileAllowed文件允许上传的格式
    
        desc = StringField(validators=[InputRequired()])#文件描述一定要填写
    Form类的代码
    from flask import Flask,request,render_template
    #验证文件安全
    from werkzeug.utils import secure_filename
    #获取服务器的图片
    from flask import send_from_directory
    #可以把两个不可变的字典组成一个字典
    from werkzeug.datastructures import CombinedMultiDict
    from forms_file import Upload
    
    import os
    
    app = Flask(__name__)
    
    UPLOAD_PATH = os.path.join(os.path.dirname(__file__),'image')
    
    
    @app.route('/')
    def hello_world():
        return 'hello world'
    
    
    #上传文件api
    @app.route('/upload/',methods=['GET',"POST"])
    def upload():
        if request.method == "GET":
            return render_template('upload.html')
        else:
            #request.form类型是不可变的字典,通过CombinedMultiDict,就可以把文件
            # 上传的数据都传递给Upload这个类了
            upload_file = Upload(CombinedMultiDict([request.form,request.files]))
         if upload_file.validata():
            desc = upload_file.desc.data
            avatar = upload_file.avatar.data
     
    # desc = request.form.get('desc') # avater = request.files.get('avater') # import uuid # filename_split = avater.filename.split('.') # filename_uuid = '{0}{1}{2}'.format(uuid.uuid1(),".",filename_split[1]) # filename = secure_filename(filename_uuid) # avater.save(os.path.join(UPLOAD_PATH,filename)) # print(desc) # return '上传成功' #获取图片api @app.route('/image/<uuid:filename>') def get_image(filename): return send_from_directory(UPLOAD_PATH,filename) if __name__ == '__main__': app.run(debug=True)

  • 相关阅读:
    ElasticSearch 2 (10)
    zookeeper 配置
    zookeeper
    ES 聚合函数
    win 7安装 linux
    Elasticsearch分布式搜索集群配置
    Elasticsearch 插件安装
    为Elasticsearch添加中文分词,对比分词器效果
    .net 4.0 网站发布(转)
    ssm 网页
  • 原文地址:https://www.cnblogs.com/wuheng-123/p/9741868.html
Copyright © 2011-2022 走看看