【flask】表单-上传文件

依赖:

flask-wtf

 

upload_case.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data">
    {{form.csrf_token}}

    {{form.case}}<br>
    {{form.submit}}<br>
</form>
</body>
</html>

froms.py

from flask_wtf import FlaskForm
from wtforms import  StringField,SubmitField
from flask_wtf.file import FileField,FileRequired,FileAllowed
from wtforms.validators import DataRequired,Length

class UploadCaseForm(FlaskForm):
    case = FileField('Upload Case',validators=[FileRequired(),FileAllowed(['xlsx'])])
    submit = SubmitField('提交')

upload_case.py

from flask import  Flask,render_template,flash,session
from demo.forms import UploadCaseForm
import os,uuid

app = Flask(__name__)
app.secret_key='secret string'
app.config['UPLOAD_PATH']=os.path.join(app.root_path,'uploads')


@app.route('/basic',methods=['GET','POST'])
def basic():
    form = UploadCaseForm()
    if form.validate_on_submit():
        f=form.case.data
        filename=random_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_PATH'],filename))
        flash('Upload Success')
        session['filenames']=[filename]
        return "上传成功"

    return render_template('upload_case.html',form=form)

def random_filename(filename):
    ext=os.path.split(filename)[1]
    new_filename=uuid.uuid4().hex+ext
    return new_filename

if __name__=='__main__':
    app.run(debug=True)

 

posted @ 2019-11-14 16:59  wangju003  阅读(403)  评论(0编辑  收藏  举报