1. 程式人生 > >flask獲取表單以enctype="multipart/form-data"格式傳送的資料

flask獲取表單以enctype="multipart/form-data"格式傳送的資料

最早的HTTP POST是不支援檔案上傳的,給程式設計開發帶來很多問題。但是在1995年,ietf出臺了rfc1867,也就是《RFC 1867 -Form-based File Upload in HTML》,用以支援檔案上傳。所以Content-Type的型別擴充了multipart/form-data用以支援向伺服器傳送二進位制資料。因此傳送post請求時候,表單屬性enctype共有二個值可選,這個屬性管理的是表單的MIME編碼:

①application/x-www-form-urlencoded(預設值)
②multipart/form-data
其實form表單在你不寫enctype屬性時,也預設為其添加了enctype屬性值,預設值是enctype=”application/x- www-form-urlencoded”.

當需要上傳檔案時,需要在form 標籤中包含enctype=”multipart/form-data”和method=”post”屬性,表單就會以二進位制形式提交到伺服器
flask 通過request.form.get("keyword")獲取上文提到的兩種格式的資料,通過request.files.get("filename")來獲取單個檔案通過reuquest.files.getlist("files[]")來獲取多個上傳檔案

在html程式碼中,多個上傳檔案可以通過兩種方式獲取
①設定多個<input>標籤,需保證name屬性值相同,伺服器通過reuquest.files.getlist(“files[]”)獲取這一組檔案

<input type="file" name ="file[]">
<input type="file" name ="file[]">
<input type="file" name ="file[]">

②設定一個<input type="file" multiple="multiple" name="file[]">,如此可向一個新增檔案按鈕中新增多個檔案,伺服器依然通過reuquest.files.getlist(“files[]”)獲取這一組檔案

示例程式碼
HTML:

<!DOCTYPE html>
<html> <head> <meta charset="utf-8"></meta> <title>測試表單</title> </head> <body> <form method="POST" action="http://127.0.0.1:5000/form/new" enctype="multipart/form-data"> <p>ID: <input type="text" name="id" /></p> <p>body: <input type="text" name="body" /></p> <p>param1: <input type="text" name="param1" /></p> <input type="file" name="imgs[]"> <input type="file" name="imgs[]"> <input type="file" name="imgs[]"> <br /> <input type="submit" value="Submit" /> </form> </body> </html>

fpython程式碼:

import os
from config import basedir #defined in config
                           #basedir = os.path.abspath(os.path.dirname(__file__))

@api.route("/form/new")
def new_form():
#save image file
    imgs = request.files.getlist()
    path = basedir+"/static/imgs/"
    if not os.path.exists(path):
        os.mkdir(path)
    for img in imgs:
        file_path = path+img.filename
        img.save(file_path)
    #save other parameter
    id = request.form.get("id")
    body = request.form.get("body")
    param1 = request.form.get("body")
    print "id:"+str(id)
    print "body:"+str(body)
    print :param1:"+str(param1)
    return jsonify({})