bootstrap-fileinput是一款非常优秀的HTML5文件上传插件,支持文件预览、多选等一系列特性。
一款非常优秀的HTML5文件上传插件,支持bootstrap 3.x 和4.x版本,具有非常多的特性:多文件选择。这个插件能最简单的帮你完成文件上传功能,且使用bootstrap样式。还支持多种文件的预览,images, text, html, video, audio, flash。
bootstrap-fileinput支持form方式和ajax方式两种上传文件,可以看到上传进度。支持拖拽的方式添加和删除文件。
不过关于flask对bootstrap-fileinput支持的资料不多。对于ajax、flask和bootstrap-fileinpu使用更是少之又少,本文只是浅尝辄止。
form提交方式的前端代码
<form method="POST" role="form" action = "/upload" enctype="multipart/form-data"> example6<label for="input-6a">Large Input Group</label> <div class="file-loading"> <input id="input-b6a" name="input-b6a[]" type="file" accept="image/*" multiple> </div></form>
$(document).ready(function() {
$("#input-b6a").fileinput({
allowedFileExtensions: ['jpg', 'png', 'gif'],
uploadAsync: false, overwriteInitial: false, minFileCount: 1, maxFileCount: 5, initialPreviewAsData: true // identify if you are sending pre });});
flask后端处理代码
# 文件上传 form方式@app.route('/upload', methods=['GET', 'POST'])
def upload():
if request.method == 'GET':
return render_template('upload.html')
elif request.method == 'POST':
print('upload post')
if 'input-b6a[]' not in request.files:
return "No file part" files = request.files.getlist('input-b6a[]')
for file in files:
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return 'file uploaded successfully'
ajax的提交方式,注意js代码为uploadUrl
example6<label for="input-6a">Large Input Group</label><div class="file-loading"> <input id="input-b6a" name="input-b6a[]" type="file" accept="image/*" multiple></div>
$(document).ready(function() {
$("#input-b6a").fileinput({
allowedFileExtensions: ['jpg', 'png', 'gif'], uploadUrl: "/uploadprocess", uploadAsync: false, overwriteInitial: false, minFileCount: 1, maxFileCount: 5, initialPreviewAsData: true // identify if you are sending pre });});
ajax的后端代码,注意返回值不一样
# 文件上传 ajax方式@app.route('/uploadprocess', methods=['GET', 'POST'])
def uploadprocess():
print('upload post')
if 'input-b6a[]' not in request.files:
return jsonify({"errno": 100, "errmsg": "无文件"})
files = request.files.getlist('input-b6a[]')
for file in files:
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return jsonify({"errno": 0, "errmsg": "上传成功"})
上传后的图片