參考flask官方文檔:http://flask.pocoo.org/docs/0.12/patterns/fileuploads/
- boot.py
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Author : changyanlong
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__) # 當(dāng)前文件所在路徑
basepath = sys.path[0] # 項(xiàng)目的根目錄 boot_main.py目錄
upload_path = os.path.join(basepath, 'static\uploads',secure_filename(f.filename)) #注意:沒(méi)有的文件夾一定要先創(chuàng)建布近,不然會(huì)提示沒(méi)有該路徑
f.save(upload_path)
return redirect(url_for('upload'))
return render_template('upload.html')
if __name__ == '__main__':
app.run(debug=True)
- upload.html
<!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>