Flask-上传文件和访问上传的文件

 1.1.上传文件和访问上传的文件

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

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.html

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

 

1.2.使用flask-wtf验证上传的文件

forms.py

 
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)
 

 

posted @ 2018-12-18 21:01  Hear7  阅读(4333)  评论(0编辑  收藏  举报