Bootstrap file input组件是对HTML5标准的file input组件封装的一个js插件(以下对于file input组件简称插件)。该插件是以Bootstrap系列文件为基础的,可以和Bootstrap组件无缝对接。同时提供了非常丰富的文件上传、下载和预览等相关功能。
本文所涉及的各种样例均以file-input插件4.5.2版本为基础。
1、上传方式的简介
file input组件提供两种模式、三种类型的上传文件的方式。第一种模式是同步模式上传,即file input组件中的文件,在其所属的form表单内,随input组件中的其他元素一起提交到后端。这与传统的文件上传比较接近。第二种模式是Ajax模式上传,即file input组件中的文件,在其所属的form表单提交完成后,页面发起另一次http请求,将file input组件中的文件另行提交到后端。如果上传的文件有多个,在这种模式下,又分为两种类型。第一种类型是异步Ajax上传,即将多个文件以每个文件单独使用一次http请求的形式上传到后端。也就是说,多个文件需要多次http请求才能将文件全部上传完成。第二种类型是同步Ajax上传,即不论有多少个文件,插件都以一次http请求完成文件的上传。
2、页面导入文件,包括CSS、js文件。
<link rel="stylesheet" type="text/css" href="js/bootstrap-fileinput-4.5.2/css/fileinput.min.css" />
<script src="js/bootstrap-fileinput-4.5.2/js/fileinput.min.js"></script>
<script src="js/bootstrap-fileinput-4.5.2/js/locales/zh.js"></script>
由于版本变化,也可以参考file-input插件官网的说明:https://plugins.krajee.com/file-input#usage
3、定义html元素
<div class="form-group">
<label class="control-label">附件上传:</label>
<div class="m-b-15">
<input id="uattachment" type="file" name="uattachment" multiple class="file-loading">
<div id="errorBlockAttachment" class="help-block"></div>
</div>
</div>
特别说明,此处的元素有用到bootstrap的样式,请各位自行添加相关css文件。在这里,我们定义了一个id为uattachment的,type为file的input组件,后面的代码将以此为核心进行封装。
4、配置插件
在页面的js代码部分写入如下代码:
$("#uattachment").fileinput({
language: 'zh',
elErrorContainer: "#errorBlockAttachment",
uploadUrl: "wapi/fileupload",
showPreview: true,
showCaption: false,
showRemove: true,
showUpload: false,
showCancel: false,
showBrowse: false,
showUploadedThumbs: false,
browseOnZoneClick: true,
allowedPreviewTypes: null,
preferIconicPreview: true,
overwriteInitial: false,
initialPreview:preview,
initialPreviewConfig:previewConfig,
previewFileIconSettings: Files_ICON,
previewFileExtSettings: Files_TestFunc,
fileActionSettings: {
showUpload: false,
showZoom: false,
showDownload: true,
downloadIcon: '<i class="glyphicon glyphicon-download"></i>',
downloadClass: 'btn btn-kv btn-default btn-outline-secondary',
downloadTitle: '下载附件'
},
slugCallback: function(text) {
if(text === undefined || text === null || text.length === 0) return '';
return String(text).replace(/[\/:\*\?\\\|<>"']/g, '_');
},
uploadExtraData: function(previewId, index) {
return {
docId:$('#docId').val(), type:1};
}
});
通过上述代码,插件将对上文提到的id为uattachment的组件进行封装。
下面将对上述选项进行逐一解释:
$("#uattachment").fileinput({
...));
这里是调用插件的fileinput方法,对id="uattachment"的jQuery对象进行fileinput组件的包装。以下所有的选项都是对包装的方式进行配置。
language: 'zh'
这里的配置项是对语言的配置,这里的要求是语言的配置选项必须符合ISO的形式。同时,需要将对应的语言的js文件加载到页面中,且此语言文件的位置必须在导入的fileinput.js之后。
样例配置如下:
<script src="js/bootstrap-fileinput-4.5.2/js/fileinput.min.js"></script>
<