Flask学习笔记(3):上传文件
flask上传文件,如上传个人头像,流程:
前端选择并提交文件——后端通过表单接收文件——验证文件的合法性并保存——url访问文件
代码:
upload.py:
1 from flask import Flask,request,render_template 2 import os 3 from flask import send_from_directory 4 from forms import UploadForm 5 from werkzeug.datastructures import CombinedMultiDict 6 7 upload_path = os.path.join(os.path.dirname(__file__), 'images') #获取图片所在的文件夹绝对路径 8 print(upload_path) 9 app = Flask(__name__) 10 @app.route('/') 11 def hello_world(): 12 return "hello world" 13 14 @app.route('/upload',methods=['GET','POST']) 15 def upload(): 16 '''上传文件''' 17 if request.method == 'GET': 18 return render_template('upload.html') 19 else: 20 form =UploadForm(CombinedMultiDict([request.form,request.files])) 21 # 由于文件要通过request.files来获取,字段则直接通过request.form来获取,然而这里的request.form和request.files的类型都是一样的, 22 # 都是多字典的型的: <class 'werkzeug.datastructures.ImmutableMultiDict'>, 23 # 如 ImmutableMultiDict([('avatar', < FileStorage: 'hehe.jpg' ('image/jpeg') >)]) 24 # 这里通过特殊的方法将他们结合到一起去验证 25 if form.validate(): 26 avatar = request.files.get("avatar") # 获取form表单上传的文件 27 filename = os.path.join(upload_path,avatar.filename) #获取文件绝对路径 28 avatar.save(filename) # 保存文件 29 return "上传成功" 30 else: 31 return return_err_message('upload.html',form) 32 33 def return_err_message(template,form): 34 ''' 返回错误提示信息'''36 err_message = list(form.errors.values())[0][0]38 content = { 39 'err_message': err_message 40 } 41 return render_template(template, **content) 42 @app.route("/images/<filename>") 43 def get_image(filename): 44 ''' url访问文件 ''' 45 return send_from_directory(upload_path,filename) 46 47 if __name__ == '__main__': 48 app.run()
forms.py:
1 from wtforms import Form,StringField,FileField 2 from wtforms.validators import InputRequired 3 from flask_wtf.file import FileRequired,FileAllowed 31 class UploadForm(Form): 32 """上传文件验证""" 33 avatar = FileField(validators=[FileRequired(message="文件不能为空"),FileAllowed(["jpg","png","gif"],message="上传文件格式不正确")]) 34 signature = StringField(validators=[InputRequired(message="个性签名不能为空")])
upload.html:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>上传文件</title> 6 </head> 7 <body> 8 <form action="" method="post" enctype="multipart/form-data"> 9 <table> 10 <tr> 11 <td>上传个人头像:</td> 12 <td><input type="file" name="avatar"></td> 13 </tr> 14 <tr> 15 <td>个性签名:</td> 16 <td><input type="text" name="signature"></td> 17 </tr> 18 <tr> 19 <td></td> 20 <td><input type="submit" value="点击上传"></td> 21 </tr> 22 </table> 23 </form> 24 {% if err_message %} 25 <p style="color: red">{{ err_message }}</p> 26 {% endif %} 27 </body> 28 </html>