flask文件上传

流程

1. 上传的文件request.files拿取

2. 可以通过WTForms表单验证

3. 通过secure_filename (from werkzeug.utils import secure_filename ), 验证文件名称是否安全

4. 验证完毕的数据直接保存fileobj.save(path,filename)

 

5. 拿取数据:send_from_directory(from flask import send_from_directory)    return send_from_directory(UPLOAD_PATH,filename)

 

代码示例

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__)

UPLOAD_PATH = os.path.join(os.path.dirname(__file__),'images')



@app.route('/upload/',methods=['GET','POST'])
def upload():
    if request.method == 'GET':
        return render_template('upload.html')
    else:
        form = UploadForm(CombinedMultiDict([request.form,request.files]))  #拿到form中验证
        if form.validate():
            desc = form.desc.data
            avatar = form.avatar.data  # 拿到验证完成的对象
            filename = secure_filename(avatar.filename)  # 验证名称
            avatar.save(os.path.join(UPLOAD_PATH,filename))  # 保存
            print(desc)
            return '文件上传成功'
        else:
            print(form.errors)
            return "fail"

@app.route('/images/<filename>/')
def get_image(filename):
    return send_from_directory(UPLOAD_PATH,filename)  # 发送对象

flaskapp.py
flaskapp.py

 

from wtforms import Form,FileField,StringField
from wtforms.validators import InputRequired
# flask_wtf
from flask_wtf.file import FileRequired,FileAllowed

class UploadForm(Form):
    avatar = FileField(validators=[FileRequired(),FileAllowed(['jpg','png','gif'])])
    desc = StringField(validators=[InputRequired()])
forms.py