【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)
@ute('/', methods=['POST', 'GET'])
def process():
hod == 'POST':
f = ('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'))
getsavefilename
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)
basedir = os.path.abspath(os.path.dirname(__file__))
uploadDir = os.path.join(basedir, 'static/uploads')
@ute('/', methods=['POST', 'GET'])
def process():
hod == 'POST':
f = ('fileupload')
if not ists(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)
basedir = os.path.abspath(os.path.dirname(__file__))
uploadDir = os.path.join(basedir, 'static/uploads')
@ute('/', methods=['POST', 'GET'])
def process():
hod == 'POST':
f = ('fileupload')
if not ists(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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。