【Flask】flask实现上传文件并在前端显示

 用表单实现文件上传功能,上传至目录:static/uploads文件夹下,并对flash消息分类显示

文件组织:

helloworld:

app.py

/templates/base.html

/static/uploads

 

app.py文件

from flask import Flask, render_template, request, flash, redirect, url_for
from flask_bootstrap import Bootstrap
import os
from werkzeug.utils import secure_filename

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

@app.route('/', methods=['POST', 'GET'])
def process():
    if request.method == 'POST':
        f = request.files.get('fileupload')
        basepath = os.path.dirname(__file__)
        if f:
            filename = secure_filename(f.filename)
            types = ['jpg', 'png', 'tif']
            if filename.split('.')[-1] in types:
                uploadpath = os.path.join(basepath, 'static/uploads', filename)
                f.save(uploadpath)
                flash('Upload Load Successful!', 'success')
            else:
                flash('Unknown Types!', 'danger')
        else:
            flash('No File Selected.', 'danger')
        return redirect(url_for('process'))
    return render_template('base.html')


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

base.html文件

{% extends "bootstrap/base.html" %}
{% block title %}Flask-Upload{% endblock %}

{% block content %}
    
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %}
{{ message }}
{% endfor %} {% endif %} {% endwith %}
{% endblock %}

 没有选择文件的提示:

【Flask】flask实现上传文件并在前端显示_第1张图片

 不是jpg/tif/png类型时的提示

 【Flask】flask实现上传文件并在前端显示_第2张图片

 上传成功提示

【Flask】flask实现上传文件并在前端显示_第3张图片


更新:若上传文件夹不存在则创建uploads文件夹,全屏显示上传的图片

app.py

from flask import Flask, render_template, request, flash, redirect, url_for, make_response
from flask_bootstrap import Bootstrap
import os
from werkzeug.utils import secure_filename

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

basedir = os.path.abspath(os.path.dirname(__file__))
uploadDir = os.path.join(basedir, 'static/uploads')


@app.route('/', methods=['POST', 'GET'])
def process():
    if request.method == 'POST':
        f = request.files.get('fileupload')
        if not os.path.exists(uploadDir):
            os.makedirs(uploadDir)
        if f:
            filename = secure_filename(f.filename)
            types = ['jpg', 'png', 'tif']
            if filename.split('.')[-1] in types:
                uploadpath = os.path.join(uploadDir, filename)
                f.save(uploadpath)
                flash('Upload Load Successful!', 'success')
                image_data = open(uploadpath, 'rb').read()
                response = make_response(image_data)
                response.headers['Content-Type'] = 'image/png'
                return response
            else:
                flash('Unknown Types!', 'danger')
        else:
            flash('No File Selected.', 'danger')
        return redirect(url_for('process'))
    return render_template('base.html')


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

base.html

{% extends "bootstrap/base.html" %}
{% block title %}Flask-Upload{% endblock %}

{% block content %}
    
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} {% if category in ["success","danger"] %}
{{ message }}
{% endif %} {% endfor %} {% endif %} {% endwith %}
{% endblock %}

【Flask】flask实现上传文件并在前端显示_第4张图片


更新:在页面中设置一个img标签显示图片,若上传成功则显示图片,则没有上传则不显示

思路:在app.py中向base.html返回一个文件名,base.html中用接收文件名用url_for找到该文件

app.py

from flask import Flask, render_template, request, flash, redirect, url_for, make_response
from flask_bootstrap import Bootstrap
import os
from werkzeug.utils import secure_filename

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

basedir = os.path.abspath(os.path.dirname(__file__))
uploadDir = os.path.join(basedir, 'static/uploads')


@app.route('/', methods=['POST', 'GET'])
def process():
    if request.method == 'POST':
        f = request.files.get('fileupload')
        if not os.path.exists(uploadDir):
            os.makedirs(uploadDir)
        if f:
            filename = secure_filename(f.filename)
            types = ['jpg', 'png', 'tif']
            if filename.split('.')[-1] in types:
                uploadpath = os.path.join(uploadDir, filename)
                f.save(uploadpath)
                flash('Upload Load Successful!', 'success')
            else:
                flash('Unknown Types!', 'danger')
        else:
            flash('No File Selected.', 'danger')
        return render_template('base.html', imagename=filename)
    return render_template('base.html')


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

base.html

{% extends "bootstrap/base.html" %}
{% block title %}Flask-Upload{% endblock %}

{% block content %}
    
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} {% if category in ["success","danger"] %}
{{ message }}
{% endif %} {% endfor %} {% endif %} {% endwith %}
{% if imagename %} {% endif %}
{% endblock %}

效果展示:

【Flask】flask实现上传文件并在前端显示_第5张图片


上传文件控件优化:

app.py

from flask import Flask, render_template, request, flash, redirect, url_for, make_response
from flask_bootstrap import Bootstrap
import os
from werkzeug.utils import secure_filename

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

basedir = os.path.abspath(os.path.dirname(__file__))
uploadDir = os.path.join(basedir, 'static/uploads')


@app.route('/', methods=['POST', 'GET'])
def process():
    if request.method == 'POST':
        f = request.files.get('selectfile')
        if not os.path.exists(uploadDir):
            os.makedirs(uploadDir)
        if f:
            filename = secure_filename(f.filename)
            types = ['jpg', 'png', 'tif']
            if filename.split('.')[-1] in types:
                uploadpath = os.path.join(uploadDir, filename)
                f.save(uploadpath)
                flash('Upload Load Successful!', 'success')
                return render_template('base.html', imagename=filename)
            else:
                flash('Unknown Types!', 'danger')
        else:
            flash('No File Selected.', 'danger')
    return render_template('base.html')


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

base.html

{% extends "bootstrap/base.html" %}
{% block title %}Flask-Upload{% endblock %}

{% block content %}
{% with messages = get_flashed_messages(with_categories=true) %} {% if messages %} {% for category, message in messages %} {% if category in ["success","danger"] %}
{{ message }}
{% endif %} {% endfor %} {% endif %} {% endwith %}
浏览
{% if imagename %} {% endif %}
{% endblock %} {% block scripts %} {{ super() }} {% endblock %}

【Flask】flask实现上传文件并在前端显示_第6张图片

 

 

 

 

参考:

http://docs.jinkan.org/docs/flask/patterns/flashing.html#message-flashing-pattern

你可能感兴趣的:(Python)