今天记下使用Flask如何长传单个或多个文件。
以上传头像为例
配置上传路径:
# 上传文件存储的目录
MEDIA_LEYU_UPLOAD = os.path.join(os.getcwd(), 'upload')
#头像上传路径
UPLOAD_AVATAR_FOLDER = os.path.join(MEDIA_LEYU_UPLOAD, 'avatar')
表单设计
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed, FileRequired
from wtforms import SubmitField
class SetavatarForm(FlaskForm):
avatar = FileField(
'用户头像', validators=[FileRequired(), FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')]
)
submit = SubmitField('确认')
模板
<form class="form-horizontal" method="POST" enctype="multipart/form-data" >
{{ form.csrf_token }}
<div class="col-md-4 col-sm-4 col-xs-12 input-width-ie7">
{{ form.avatar(class="form-control") }}
</div>
<div class="col-md-4 col-sm-4 col-xs-12 col-sm-offset-3">
{{ form.submit(class="btn btn-success") }}
</div>
</form>
视图函数
@user.route('/set-avatar', endpoint='SetAvatar', methods=['GET', 'POST'])
def set_avatar():
form = SetavatarForm()
if request.method == 'POST' and form.validate_on_submit():
file_obj = request.files.get('avatar', '')
#获得文件名
file_name = file_obj.filename
#获得文件格式
file_postfix = file_name.split('.')[-1]
#对文件进行重命名
store_filename = '{}.{}'.format(str(current_user.id), file_postfix)
#检查文件保存路径
if not os.path.exists(constant.UPLOAD_AVATAR_FOLDER):
os.makedirs(constant.UPLOAD_AVATAR_FOLDER)
path = os.path.join(constant.UPLOAD_AVATAR_FOLDER, store_filename)
#保存文件
file_obj.save(path)
#便于远程访问使用URI保存
url = '{}{}'.format(request.url_root, url_for('main.AvatarUpload', filename=store_filename)[1:])
try:
current_user.avatar = url
db.session.commit()
except Exception as err:
raise err
return render_template('user/set_avatar.html', form=form)
elif not form.validate_on_submit():
flash("请上传jpg或png格式的头像")
return render_template('user/set_avatar.html', form=form)
else:
return render_template('user/set_avatar.html', form=form)
大致过程如上,并未进行安全认证
如果是多文件上传要注意两点:
模板文件要配置一项:
{{ form.screen_shot(multiple="multiple") }}
这样才能够使用多文件上传
另外多文件上传后为文件列表,获取文件方法如下:
file_obj = request.files.getlist('screen_shot')
for file in file_obj:
file_name = file.filename