Flask-Uploads文件上传的简单使用
2017-02-09 本文已影响7120人
宝宝家的隔壁老王
flask-uploads 是封装的 flask里的文件上传功能,此处以实现用户头像上传为例
官方文档介绍:点我
1、安装 flask-uploads 模块
pip install flask-uploads
2、新建一个 demo.py 文件,作为应用
先导入次此处需要用到的库:
from flask_uploads import UploadSet, IMAGES, configure_uploads, ALL
from flask import request, Flask, redirect, url_for, render_template
import os
3、生成 app
app = 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 实例 photos
configure_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、运行 app
app.run()
完整的代码如下:
from flask_uploads import UploadSet, IMAGES, configure_uploads, ALL
from flask import request, Flask, redirect, url_for, render_template
import os
app = Flask(__name__)
app.config['UPLOADED_PHOTO_DEST'] = os.path.dirname(os.path.abspath(__file__))
app.config['UPLOADED_PHOTO_ALLOW'] = IMAGES
def 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) 进行加载。