对文件上传使用表单验证
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)