【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 %}
    <div class="container">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    <div class="alert alert-{{ category }}">
                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                        {{ message }}
                    </div>
                {% endfor %}
            {% endif %}
        {% endwith %}
                <form method="post" enctype="multipart/form-data">
                    <input type="file" name="fileupload">
                    <input type="submit" value="上傳">
                </form>
    </div>
{% endblock %}

 沒有選擇文件的提示:

 不是jpg/tif/png類型時的提示

 

 上傳成功提示


更新:若上傳文件夾不存在則創建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 %}
    <div class="container">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    {% if category in ["success","danger"] %}
                        <div class="alert alert-{{ category }}">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            {{ message }}
                        </div>
                    {% endif %}
                {% endfor %}
            {% endif %}
        {% endwith %}
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="fileupload">
            <input type="submit" value="上傳">
        </form>
    </div>
{% endblock %}


更新:在頁面中設置一個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 %}
    <div class="container">
        {% with messages = get_flashed_messages(with_categories=true) %}
            {% if messages %}
                {% for category, message in messages %}
                    {% if category in ["success","danger"] %}
                        <div class="alert alert-{{ category }}">
                            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                            {{ message }}
                        </div>
                    {% endif %}
                {% endfor %}
            {% endif %}
        {% endwith %}
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="fileupload">
            <input type="submit" value="上傳">
        </form>
        {% if imagename %}
            <img src="{{ url_for('static',filename='uploads/'+imagename) }}" width="300px" height="300px"/>
        {% endif %}
    </div>
{% endblock %}

效果展示:


上傳文件控件優化:

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 %}
<div class="container">
    {% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
    {% for category, message in messages %}
    {% if category in ["success","danger"] %}
    <div class="alert alert-{{ category }}">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
        {{ message }}
    </div>
    {% endif %}
    {% endfor %}
    {% endif %}
    {% endwith %}
    <form method="post" enctype="multipart/form-data">
        <input id="lefile" type="file" style="display:none" name="selectfile">
        <div class="input-append form-inline">
            <input id="photoCover" class="input-large form-control" type="text"
                   style="height:34px;width:60vw;border:2px #337ab7 solid"
                   placeholder="請選擇影像">
            <a class="btn btn-primary" οnclick="$('input[id=lefile]').click();">瀏覽</a>
            <button type="submit" class="btn btn-primary">上傳</button>
        </div>

    </form>
    {% if imagename %}
    <img src="{{ url_for('static',filename='uploads/'+imagename) }}" width="300px" height="300px"/>
    {% endif %}
</div>
{% endblock %}
{% block scripts %}
{{ super() }}
<script type="text/javascript">
    $('input[id=lefile]').change(function () {
        $('#photoCover').val($(this).val());
    });

    $("#photoCover").attr('autocomplete', 'off')
</script>
{% endblock %}

 

 

 

 

參考:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章