1. 程式人生 > >falsk之檔案上傳

falsk之檔案上傳

 

在使用flask定義路由完成檔案上傳時,定義upload檢視函式

from flask import Flask, render_template
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)
app.debug = True
app.secret_key = 'helloworld!!'

@app.route('/')
def hello_world():
    return 'Hello World!'

@app.route('/upload
',methods=['GET','POST']) def upload(): if request.method == 'POST': f = request.files['file'] base_path = os.path.abspath(os.path.dirname(__file__)) upload_path = os.path.join(base_path,'static\uploads') f.save(upload_path,secure_filename(f.filename))
return "檔案上傳成功!!" return render_template('upload.html') @app.errorhandler(404) def page_not_found(error): return render_template('404.html'),404 if __name__ == '__main__': app.run(debug=True)

upload.html前端頁面的內容為

<!DOCTYPE html>
<html lang="en">
<head>
    <
meta charset="UTF-8"> <title>檔案上傳</title> </head> <body> <h1>檔案上傳示例</h1> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上傳"> </form> </body> </html>

啟動專案,用瀏覽器開啟http://127.0.0.1:5000/upload頁面,前端頁面顯示如圖所示

選擇要上傳的檔案

檔案選擇完畢後,點選上傳,flask會丟擲異常,提供沒有許可權

修改upload檢視函式

@app.route('/upload',methods=['GET','POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        base_path = os.path.abspath(os.path.dirname(__file__))
        upload_path = os.path.join(base_path,'static\uploads',secure_filename(f.filename))
        f.save(upload_path)
        return "檔案上傳成功!!"
    return render_template('upload.html')

再次進行檔案上傳,選中檔案後,點選上傳按鈕,可以看到

由此可以看出,檔案已經成功上傳,此時檢視專案static/uploads目錄,可以看到上傳的圖片已經儲存在flask專案中了

由此可以在Flask專案中完成檔案上傳功能!!