flask 文件上传

 

test_flask.py

from flask import Flask,render_template,request,redirect,url_for,flash
from werkzeug.utils import secure_filename      #导入安全函数
import os

app = Flask(__name__)
app.config['SECRET_KEY'] = os.urandom(24)

ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'jpeg', 'gif'])      #设置可以上传的文件

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS    #返回结果为false或者true [1]为获取的文件的后缀名



@app.route('/')
def hello_world():
    return 'Hello World!'


@app.route('/upload/',methods=['GET','POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        #print (f)
        if f and allowed_file(f.filename):  
            app.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(__file__),'static/uploads')    #设置上传文件到服务器的路径
            #print(app.config['UPLOAD_FOLDER'])
            if not os.path.exists(app.config['UPLOAD_FOLDER']):            #如果路径不存在则创建
                os.makedirs(app.config['UPLOAD_FOLDER'])
            upload_file_name = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)  #上传的文件保存的名称,如果这里用secure_filename函数,对于中文文件,最后只保存为k后缀名
            #print(secure_filename(f.filename))
            f.save(upload_file_name)
            flash("文件上传成功", 'ok')
            return redirect(url_for('upload'))
        flash("文件上传失败,无效的格式 %s" % f.filename.rsplit('.', 1)[1],'err')
        return redirect(url_for('upload'))
    return render_template('upload.html')


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

 

upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h2>文件上传示例</h2>
    <form action="" enctype='multipart/form-data' method='POST'>
        <input type="file" name="file">
        <input type="submit" value="上传">
    </form>
    {% for v in get_flashed_messages(category_filter=['err']) %}
        <p style="color:red;">{{ v }}</p>
    {% endfor %}
    {% for v in get_flashed_messages(category_filter=['ok']) %}
        <p style="color:green;">{{ v }}</p>
    {% endfor %}
</body>
</html>

 

posted @ 2018-03-13 15:28  FRESHMANS  阅读(270)  评论(0编辑  收藏  举报