upload_file_demo.pyhtml
from flask import Flask,request,render_template import os from werkzeug.utils import secure_filename from flask import send_from_directory app = Flask(__name__) #新建images文件夾,UPLOAD_PATH就是images的路徑 UPLOAD_PATH = os.path.join(os.path.dirname(__file__),'images') @app.route('/upload/',methods=['GET','POST']) def settings(): if request.method == 'GET': return render_template('upload.html') else: desc = request.form.get('desc') avatar = request.files.get('avatar') # 對文件名進行包裝,爲了安全,不過對中文的文件名顯示有問題 filename = secure_filename(avatar.filename) avatar.save(os.path.join(UPLOAD_PATH,filename)) print(desc) return '文件上傳成功' #訪問上傳的文件 #瀏覽器訪問:http://127.0.0.1:5000/images/django.jpg/ 就能夠查看文件了 @app.route('/images/<filename>/',methods=['GET','POST']) def get_image(filename): return send_from_directory(UPLOAD_PATH,filename) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run(debug=True)
upload.htmldjango
<form action="" method="post" enctype="multipart/form-data"> <table> <tbody> <tr> <td>頭像:</td> <td><input type="file" name="avatar"></td> </tr> <tr> <td>描述:</td> <td><input type="text" name="desc"></td> </tr> <tr> <td><input type="submit" value="提交"></td> </tr> </tbody> </table> </form>
forms.pyflask
from wtforms import Form,FileField,StringField from wtforms.validators import InputRequired from flask_wtf.file import FileRequired,FileAllowed class UploadForm(Form): avatar = FileField(validators=[FileRequired(), #FileRequired必須上傳 FileAllowed(['jpg','png','gif']) #FileAllowed:必須爲指定的格式的文件 ]) desc = StringField(validators=[InputRequired()])
upload_file_demo.py瀏覽器
from flask import Flask, request, render_template import os from werkzeug.utils import secure_filename from flask import send_from_directory from forms import UploadForm from werkzeug.datastructures import CombinedMultiDict app = Flask(__name__) # 新建images文件夾,UPLOAD_PATH就是images的路徑 UPLOAD_PATH = os.path.join(os.path.dirname(__file__), 'images') @app.route('/upload/', methods=['GET', 'POST']) def settings(): if request.method == 'GET': return render_template('upload.html') else: # 文件是從request,files裏面獲取,這裏使用CombinedMultiDict把form和file的數據組合起來,一塊兒驗證 form = UploadForm(CombinedMultiDict([request.form, request.files])) if form.validate(): desc = request.form.get('desc') avatar = request.files.get('avatar') # 對文件名進行包裝,爲了安全,不過對中文的文件名顯示有問題 filename = secure_filename(avatar.filename) avatar.save(os.path.join(UPLOAD_PATH, filename)) print(desc) return '文件上傳成功' else: print(form.errors) return "fail" # 訪問上傳的文件 # 瀏覽器訪問:http://127.0.0.1:5000/images/django.jpg/ 就能夠查看文件了 @app.route('/images/<filename>/', methods=['GET', 'POST']) def get_image(filename): return send_from_directory(UPLOAD_PATH, filename) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run(debug=True)