用表单实现文件上传功能,上传至目录: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" onclick="$('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