1. 程式人生 > 程式設計 >flask 實現上傳圖片並縮放作為頭像的例子

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,filename)) 語句將略縮圖片儲存到服務指定路徑。

以上這篇flask 實現上傳圖片並縮放作為頭像的例子就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。