flask上傳文件到指定路徑html
項目結構以下:python
首先是:視圖函數uload_file.py,代碼以下:flask
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask,render_template,request,redirect,url_for from werkzeug.utils import secure_filename import os app = Flask(__name__) @app.route('/upload', methods=['POST', 'GET']) def upload(): if request.method == 'POST': f = request.files['file'] basepath = os.path.dirname(__file__) # 當前文件所在路徑 print(basepath) upload_path = os.path.join(basepath, 'upload_file_dir',secure_filename(f.filename)) # 注意:沒有的文件夾必定要先建立,否則會提示沒有該路徑 print(upload_path) upload_path = os.path.abspath(upload_path) # 將路徑轉換爲絕對路徑 print(upload_path) f.save(upload_path) return redirect(url_for('upload')) return render_template('upload.html') if __name__ == '__main__': app.run(debug=True)
而後是html模板:upload.htmlapp
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>文件上傳示例</h1> <form action="" enctype='multipart/form-data' method='POST'> <input type="file" name="file"> <input type="submit" value="上傳"> </form> </body> </html>
最後能夠發現已經成功上傳函數