参考:http://www.cnblogs.com/himir/p/5940705.htmlhttps://zhuanlan.zhihu.com/p/24423891flask-uploads flask的一个文件上传扩展, 提供了UploadSet这个概念 flask-wtf(中文) 很强大的表单的扩展 flask-bootstrap bootstrap的flask扩展, 结合模版使用, 此处用到quick_form功能 from flask import Flask, render_templatefrom flask_uploads import UploadSet, IMAGES, configure_uploadsfrom flask_wtf import Formfrom wtforms import SubmitFieldfrom flask_wtf.file import FileField, FileAllowed, FileRequiredfrom flask_bootstrap import Bootstrapfrom werkzeug.utils import secure_filenameapp = Flask(__name__)# 新建一个set用于设置文件类型、过滤等set_mypic = UploadSet('mypic') # mypic# 用于wtf.quick_form()模版渲染bootstrap = Bootstrap(app)# mypic 的存储位置,# UPLOADED_xxxxx_DEST, xxxxx部分就是定义的set的名称, mypi, 下同app.config['UPLOADED_MYPIC_DEST'] = './static/img'# mypic 允许存储的类型, IMAGES为预设的 tuple('jpg jpe jpeg png gif svg bmp'.split())#DOCUMENTS = tuple('rtf odf ods gnumeric abw doc docx xls xlsx'.split())#AUDIO = tuple('wav mp3 aac ogg oga flac'.split())#TEXT = ('txt',)#DATA = ...#SCRIPTS = ...#ARCHIVES = ...#EXECUTABLES = ...#DEFAULT = TEXT + DOCUMENTS + IMAGES + DATAapp.config['UPLOADED_MYPIC_ALLOW'] = IMAGES# 把刚刚app设置的config注册到set_mypicconfigure_uploads(app, set_mypic)# 此处WTF的SCRF密码默认为和flask的SECRET_KEY一样# app.config['WTF_CSRF_SECRET_KEY'] = 'wtf csrf secret key'app.config['SECRET_KEY'] = 'xxxxx'#允许上传的文件最大为10Mpatch_request_class(app,10*1024*1024)class UploadForm(Form): # 文件field设置为‘必须的’,过滤规则设置为‘set_mypic’ upload = FileField('p_w_picpath', validators=[FileRequired('文件未选择!'), FileAllowed(set_mypic, '只能上传图片!')]) submit = SubmitField('上传')@app.route('/', methods=('GET', 'POST'))def index(): form = UploadForm() url = None if form.validate_on_submit(): filename = secure_filename(form.upload.data.filename) fileupload = set_mypic.save(form.upload.data, name=filename)url = set_mypic.url(fileupload) return render_template('index.html', form=form, url=url)if __name__ == '__main__': app.run(debug=True)-----------------------------------------安全上传方法:from flask_wtf import FlaskFormfrom flask_wtf.file import FileField, FileRequiredfrom werkzeug.utils import secure_filenameform = FlaskForm(csrf_enabled=False)WTF_CSRF_ENABLED = FalseWTF_CSRF_SECRET_KEY = 'a random string'class PhotoForm(FlaskForm): photo = FileField(validators=[FileRequired()])@app.route('/upload', methods=['GET', 'POST'])def upload(): if form.validate_on_submit(): f = form.photo.data filename = secure_filename(f.filename) f.save(os.path.join(app.instance_path, 'photos', filename)) return redirect(url_for('index')) return render_template('upload.html', form=form)------------------------------------------------ html文件:{% extends "base.html" %}{% import "bootstrap/wtf.html" as wtf %} {% block page_content %} { { wtf.quick_form(form, enctype="multipart/form-data") }}文件上传成功!
{% if url %} {% endif %} {% endblock page_content %}注:上传文件的 form 必须是 POST 方法,并且 enctype=multipart/form-data。type=file。如果使用 GET 方法,则只会上传文件名。如何将照片资源与用户进行绑定?使用轻量级 ORM 框架,peewee,使用两个字段 use_id、photo_name。将数据存储到数据库表格中。需要时可根据登录 user 的 id 获取到对应的 photo_name,然后使用 photos.url(photo_name) 进行加载。