flask 实现上传图片并缩放作为头像的例子

个人开发的 flask 论坛进入尾声,还剩最后一个上传图片更换头像功能,搞了一整天,最后终于解决了所有问题,现在记录下解决方案。

1. 上传文件

分析一下更换头像功能,我们需要做哪些事,简单的思路是:上传文件,获取文件的 url 。

文件上传的基本原理实际上很简单,基本上是:

一个带有 enctype=multipart/form-data 的 <form> 标记,标记中含有 一个 <input type=file>。

应用通过请求对象的 files 字典来访问文件。

使用文件的 save() 方法把文件永久 地保存在文件系统中。

于是可以得到我们的提供上传按钮的表单页面:

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}SYSUfm - 更换头像{% endblock %}

{% block page_content %}
<div class="page-header">
  <h1>更换你的头像</h1>
</div>
<div class="col-md-4">
  <form action="" method=post enctype=multipart/form-data>
    <input type=file name=file><br/>
    <input type=submit value=Upload>
  </form>
</div>

{% endblock %}

2. 创建略缩图

接下来我们需要有路由到这个页面的视图函数,服务器后台端的代码如下:

@main.route('/edit-avatar', methods=['GET', 'POST'])
@login_required
def change_avatar():
  if request.method == 'POST':
    file = request.files['file']
    size = (40, 40)
    im = Image.open(file)
    im.thumbnail(size)
    if file and allowed_file(file.filename):
      filename = secure_filename(file.filename)
      im.save(os.path.join(main.static_folder, 'avatar', filename))
      current_user.new_avatar_file = url_for('main.static', filename='%s/%s' % ('avatar', filename))
      current_user.is_avatar_default = False
      flash(u'头像修改成功')
      return redirect(url_for('.user', username=current_user.username))
  return render_template('change_avatar.html')

这里 main 是一个 blueprint,file = request.files['file'] 语句获得图片文件对象,将其转换为 Image 对象,通过 thumbnail 方法进行略缩。

最后 im.save(os.path.join(main.static_folder, 'avatar', filename)) 语句将略缩图片保存到服务指定路径。

以上这篇flask 实现上传图片并缩放作为头像的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。