flask-uploads 是封装的 flask里的文件上传功能,此处以实现用户头像上传为例
官方文档介绍:点我
1、安装 flask-uploads 模块pip install flask-uploads
2、新建一个 demo.py 文件,作为应用
先导入次此处需要用到的库:from flask_uploads import UploadSet, IMAGES, configure_uploads, ALLfrom flask import request, Flask, redirect, url_for, render_templateimport os
3、生成 appapp = Flask(__name__)
4、配置文件上传到的路径,以及限制上传文件的类型
app.config['UPLOADED_PHOTO_DEST'] = os.path.dirname(os.path.abspath(__file__))
app.config['UPLOADED_PHOTO_ALLOW'] = IMAGES
5、实例化 UploadSet 对象photos = UploadSet('PHOTO')
6、将 app 的 config 配置注册到 UploadSet 实例 photosconfigure_uploads(app, photos)
7、生成一个 upload 的路由
@app.route('/upload', methods=['POST', 'GET'])def upload(): if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo']) return redirect(url_for('show', name=filename)) return render_template('upload.html')
8、创建 upload.html 模板
<!doctype html><form method=POST enctype=multipart/form-data action="{{ url_for('upload') }}"> <input type=file name=photo> <input type=submit></form>
9、生成一个 show 的路由
@app.route('/photo/<name>')def show(name):
if name is None:
abort(404)
url = photos.url(name) return render_template('show.html', url=url, name=name)
10、创建 show.html 模板
<!doctype html><img src={{ url }}>
11、运行 appapp.run()
from flask_uploads import UploadSet, IMAGES, configure_uploads, ALLfrom flask import request, Flask, redirect, url_for, render_templateimport os
app = Flask(__name__)
app.config['UPLOADED_PHOTO_DEST'] = os.path.dirname(os.path.abspath(__file__))
app.config['UPLOADED_PHOTO_ALLOW'] = IMAGESdef dest(name):
return '{}/{}'.format(UPLOAD_DEFAULT_DEST, name)#app.config['UPLOAD_PHOTO_URL'] = 'http://localhost:5000/'photos = UploadSet('PHOTO')
configure_uploads(app, photos)@app.route('/upload', methods=['POST', 'GET'])def upload():
if request.method == 'POST' and 'photo' in request.files:
filename = photos.save(request.files['photo']) return redirect(url_for('show', name=filename)) return render_template('upload.html')@app.route('/photo/<name>')def show(name):
if name is None:
abort(404)
url = photos.url(name) return render_template('show.html', url=url, name=name)
app.run()
2、IMAGES 为定义的图片文件类型,其值如下: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 + DATA
4、config 里面设置的变量如何跟 UploadSet 实例对应
源码部分:def config_for_set(uset, app, default=None):
config = app.config
prefix = 'UPLOADED_%s_' % uset.name.upper()
using_defaults = False
if defaults is None:
defaults = dict(dest=None, url=None)
allow_extns = tuple(config.get(prefix + 'ALLOW', ()))
deny_extns = tuple(config.get(prefix + 'DENY', ()))
destination = config.get(prefix + 'DEST')
base_url = config.get(prefix + 'URL')
注:
上传文件的 form 必须是 POST 方法,并且 enctype=multipart/form-data。如果使用 GET 方法,则只会上传文件名。type=file。
还可以使用 patch_request_class() 方法限制上传文件的大小。如:patch_request_class(app, 32 * 1024 * 1024)
如何将照片资源与用户进行绑定?
使用轻量级 ORM 框架,peewee,使用两个字段 use_id、photo_name。将数据存储到数据库表格中。 需要时可根据登录 user 的 id 获取到对应的 photo_name,然后使用 photos.url(photo_name) 进行加载。
本文出自下面链接:
https://www.jianshu.com/p/9d6da9b76d70
转载于:https://blog.51cto.com/lookingdream/2119789