bootstrap 上传插件 fileinput 使用说明
来源于 https://blog.csdn.net/guoxinjie17/article/details/80364353
一、 引入文件
<link href="../css/bootstrap.min.css"rel="stylesheet">
<link href="../css/fileinput.css" media="all"rel="stylesheet" type="text/css" />
<scriptsrc="../js/jQuery-2.0.3.min.js"></script>
<script src="../js/fileinput.js"type="text/JavaScript"></script>
<script src="../js/bootstrap.min.js"type="text/javascript"></script>
1 $("#uploadfile").fileinput({ 2 3 language: 'zh', //设置语言 4 5 uploadUrl:"http://127.0.0.1/testDemo/fileupload/upload.do", //上传的地址 6 7 allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀 8 9 //uploadExtraData:{"id": 1, "fileName":'123.mp3'}, 10 11 uploadAsync: true, //默认异步上传 12 13 showUpload:true, //是否显示上传按钮 14 15 showRemove :true, //显示移除按钮 16 17 showPreview :true, //是否显示预览 18 19 showCaption:false,//是否显示标题 20 21 browseClass:"btn btn-primary", //按钮样式 22 23 dropZoneEnabled: false,//是否显示拖拽区域 24 25 //minImageWidth: 50, //图片的最小宽度 26 27 //minImageHeight: 50,//图片的最小高度 28 29 //maxImageWidth: 1000,//图片的最大宽度 30 31 //maxImageHeight: 1000,//图片的最大高度 32 33 //maxFileSize:0,//单位为kb,如果为0表示不限制文件大小 34 35 //minFileCount: 0, 36 37 maxFileCount:10, //表示允许同时上传的最大文件个数 38 39 enctype:'multipart/form-data', 40 41 validateInitialCount:true, 42 43 previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>", 44 45 msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!", 46 47 }).on("fileuploaded", function (event, data, previewId, index){ 48 49 50 51 });
三、 Options 说明:
|
属性名 |
属性类型 |
描述说明 |
默认值 |
|
language |
String |
多语言设置,使用时需提前引入\locales文件夹下对应的语言文件,中文zh,引入语言文件必须放在fileinput.js之后 |
'en' |
|
showCaption |
Boolean |
是否显示被选文件的简介 |
true |
|
showBrowse |
Boolean |
是否显示浏览按钮 |
true |
|
showPreview |
Boolean |
是否显示预览区域 |
true |
|
showRemove |
Boolean |
是否显示移除按钮 |
true, |
|
showUpload |
Boolean |
是否显示上传按钮 |
true, |
|
showCancel |
Boolean |
是否显示取消按钮 |
true, |
|
showClose: |
Boolean |
是否显示关闭按钮 |
true |
|
showUploadedThumbs |
Boolean |
|
true |
|
browseOnZoneClick |
Boolean |
|
false |
|
autoReplace |
Boolean |
是否自动替换当前图片,设置为true时,再次选择文件,会将当前的文件替换掉。 |
false |
|
generateFileId |
Object |
|
null |
|
previewClass |
String |
添加预览按钮的类属性 |
‘’ |
|
captionClass |
String |
|
‘’ |
|
frameClass |
String |
|
'krajee-default' |
|
mainClass |
String |
|
'file-caption-main' |
|
mainTemplate |
Object |
|
null |
|
purifyHtml |
Boolean |
|
true |
|
fileSizeGetter |
Object |
|
null |
|
initialCaption |
String |
|
'' |
|
initialPreview |
Array/Object |
|
[] |
|
initialPreviewDelimiter |
String |
|
'*$$*' |
|
initialPreviewAsData |
Boolean |
|
false |
|
initialPreviewFileType |
String |
|
'image' |
|
initialPreviewConfig |
Array/Object |
|
[] |
|
initialPreviewThumbTags |
Array/Object |
|
[] |
|
previewThumbTags |
Object |
|
{} |
|
initialPreviewShowDelete |
Boolean |
|
true |
|
removeFromPreviewOnError |
Boolean |
|
false |
|
deleteUrl |
String |
删除图片时的请求路径 |
'' |
|
deleteExtraData |
Object |
删除图片时额外传入的参数 |
{} |
|
overwriteInitial |
Boolean |
|
true |
|
previewZoomButtonIcons |
Object |
|
{ prev: '<i class="glyphicon glyphicon-triangle-left"></i>', next: '<i class="glyphicon glyphicon-triangle-right"></i>', toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>', fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>', borderless: '<i class="glyphicon glyphicon-resize-full"></i>', close: '<i class="glyphicon glyphicon-remove"></i>' }, |
|
previewZoomButtonClasses |
Object |
|
{ prev: 'btn btn-navigate', next: 'btn btn-navigate', toggleheader: 'btn btn-default btn-header-toggle', fullscreen: 'btn btn-default', borderless: 'btn btn-default', close: 'btn btn-default' }, |
|
preferIconicPreview |
Boolrean |
|
false |
|
preferIconicZoomPreview |
Boolrean |
|
false |
|
allowedPreviewTypes |
undefined |
|
undefined |
|
allowedPreviewMimeTypes |
Object |
|
null |
|
allowedFileTypes |
Object |
接收的文件后缀,如['jpg', 'gif', 'png'],不填将不限制上传文件后缀类型 |
null |
|
allowedFileExtensions |
Object |
|
null |
|
defaultPreviewContent |
Object |
|
null |
|
customLayoutTags |
Object |
|
{} |
|
customPreviewTags |
Object |
|
{} |
|
previewFileIcon |
String |
|
'<i class="glyphicon glyphicon-file"></i>' |
|
previewFileIconClass |
String |
|
'file-other-icon' |
|
previewFileIconSettings |
Object |
|
{} |
|
previewFileExtSettings |
Object |
|
{} |
|
buttonLabelClass |
String |
|
'hidden-xs' |
|
browseIcon |
String |
|
'<i class="glyphicon glyphicon-folder-open"></i> ' |
|
browseClass |
String |
|
'btn btn-primary' |
|
removeIcon |
String |
|
'<i class="glyphicon glyphicon-trash"></i>' |
|
removeClass |
String |
|
'btn btn-default' |
|
cancelIcon |
String |
|
'<i class="glyphicon glyphicon-ban-circle"></i>' |
|
cancelClass |
String |
|
'btn btn-default' |
|
uploadIcon |
String |
|
'<i class="glyphicon glyphicon-upload"></i>' |
|
uploadClass |
String |
|
'btn btn-default' |
|
uploadUrl |
String |
上传文件路径 |
null |
|
uploadAsync |
boolean |
是否为异步上传 |
true |
|
uploadExtraData |
|
上传文件时额外传递的参数设置 |
{} |
|
zoomModalHeight |
number |
|
480 |
|
minImageWidth |
String |
图片的最小宽度 |
null |
|
minImageHeight |
String |
图片的最小高度 |
null |
|
maxImageWidth |
String |
图片的最大宽度 |
null |
|
maxImageHeight |
String |
图片的最大高度 |
null |
|
resizeImage |
boolean |
|
false |
|
resizePreference |
String |
|
'width' |
|
resizeQuality |
number |
|
0.92 |
|
resizeDefaultImageType |
String |
|
'image/jpeg' |
|
minFileSize |
number |
单位为kb,上传文件的最小大小值 |
0 |
|
maxFileSize |
number |
单位为kb,如果为0表示不限制文件大小 |
0 |
|
resizeDefaultImageType |
number |
|
25600(25MB) |
|
minFileCount |
number |
表示同时最小上传的文件个数 |
0 |
|
maxFileCount |
number |
表示允许同时上传的最大文件个数 |
0 |
|
validateInitialCount |
boolean |
|
false |
|
msgValidationErrorClass |
String |
|
'text-danger' |
|
msgValidationErrorIcon |
String |
|
'<i class="glyphicon glyphicon-exclamation-sign"></i> ' |
|
msgErrorClass |
String |
|
'file-error-message' |
|
progressThumbClass |
String |
|
"progress-bar progress-bar-success progress-bar-striped active" |
|
rogressClass |
String |
|
"progress-bar progress-bar-success progress-bar-striped active" |
|
progressCompleteClass |
String |
|
"progress-bar progress-bar-success" |
|
progressErrorClass |
String |
|
"progress-bar progress-bar-danger" |
|
progressUploadThreshold |
number |
|
99 |
|
previewFileType |
String |
预览文件类型,内置['image', 'html', 'text', 'video', 'audio', 'flash', 'object',‘other‘]等格式 |
'image' |
|
elCaptionContainer |
String |
|
null |
|
elCaptionText |
String |
设置标题栏提示信息 |
null |
|
elPreviewContainer |
String |
|
null |
|
elPreviewImage |
String |
|
null |
|
elPreviewStatus |
String |
|
null |
|
elErrorContainer |
String |
|
null |
|
errorCloseButton |
String |
|
'<span class="close kv-error-close">×</span>' |
|
slugCallback |
String |
|
null |
|
dropZoneEnabled |
boolean |
是否显示拖拽区域 |
true |
|
dropZoneTitleClass |
String |
拖拽区域类属性设置 |
'file-drop-zone-title' |
|
fileActionSettings |
Object |
|
{} |
|
otherActionButtons |
String |
|
'' |
|
textEncoding |
String |
编码设置 |
'UTF-8' |
|
ajaxSettings |
Object |
|
{} |
|
ajaxDeleteSettings |
Object |
|
{} |
|
showAjaxErrorDetails |
boolean |
|
true |
四、 Method说明:
|
方法名 |
参数 |
描述 |
|
fileerror |
|
异步上传错误结果处理 $('#uploadfile').on('fileerror', function(event, data, msg) {
}); |
|
fileuploaded |
|
异步上传成功结果处理 $("#uploadfile").on("fileuploaded", function (event, data, previewId, index) {
}) |
|
filebatchuploaderror |
|
同步上传错误结果处理 $('#uploadfile').on('filebatchuploaderror', function(event, data, msg) {
}); |
|
filebatchuploadsuccess |
|
同步上传成功结果处理 $('#uploadfile').on('filepreupload', function(event, data, previewId, index) {
}); |
|
filebatchselected |
|
选择文件后处理事件 $("#fileinput").on("filebatchselected", function(event, files) { }); |
|
upload |
|
文件上传方法 $("#fileinput").fileinput("upload"); |
|
fileuploaded |
|
上传成功后处理方法 $("#fileinput").
|
|
filereset |
|
|
|
fileclear |
|
点击浏览框右上角X 清空文件前响应事件 $("#fileinput").on("fileclear",function(event, data, msg){ }); |
|
filecleared |
|
点击浏览框右上角X 清空文件后响应事件 $("#fileinput").on("filecleared",function(event, data, msg){ }); |
|
fileimageuploaded |
|
在预览框中图片已经完全加载完毕后回调的事件 |
五、 常见错误:
(1) 当点击上传后,报错,提示你必须选择最少X个文件上传。
错误原因:html中input标签元素属性:data-min-file-count="2" 设置为X个文件,限制上传文件数。
备注:图片上传比例判断
1 $("#imgFile").fileinput({}).on('fileimageloaded',function(event,previewId){ 2 var img = $('#'+previewId).find('img')[0]; 3 if (img.naturalWidth!=img.naturalHeight) { 4 alert('图片尺寸必须1:1'); 5 image_check = true; 6 $('.fileinput-remove').click(); 7 }else{ 8 image_check = false; 9 $('.fileinput-upload').show(); 10 } 11 12 })
1 $("#imgFile").fileinput({ 2 language : 'zh', 3 //uploadUrl:'../../module/uploadMod/index.php?c=upd&a=fileInputUpload&dir=image', 4 showUpload: false, //是否显示上传按钮 5 showCaption: false,//是否显示输入框 6 showRemove: true,//是否显示删除按钮 7 dropZoneEnabled: false, 8 showClose:false, 9 showDrag: false, 10 //initialPreviewShowDelete:false, 11 browseClass: "btn btn-primary", 12 allowedFileExtensions: ['jpg', 'png', 'gif'], 13 previewFileIcon: "<i class='glyphicon glyphicon-king'></i>", 14 overwriteInitial: false, 15 initialPreviewAsData: true, 16 //initialPreview: [], 17 //initialPreviewConfig:images_arr_info, 18 fileActionSettings:{ 19 showZoom: true, 20 showDrag: false, 21 showRemove:false, 22 showUpload:false 23 } 24 25 26 }).on("fileuploaded", function(event, data,previewId,index) { 27 var data = data.response; 28 image = JSON.stringify(data); 29 30 31 $("#topImg").hide().parent().hide(); 32 $('.fileinput-upload').hide(); 33 }).on('filebatchselected', function(event, files) { 34 if(files.length<=0){ 35 $('.fileinput-upload-button').hide(); 36 }else{ 37 $('.fileinput-upload-button').show(); 38 } 39 }).on('fileimageloaded',function(event,previewId){ 40 var img = $('#'+previewId).find('img')[0]; 41 if (img.naturalWidth!=img.naturalHeight) { 42 alert('图片尺寸必须1:1'); 43 image_check = true; 44 $('.fileinput-remove').click(); 45 }else{ 46 image_check = false; 47 $('.fileinput-upload').show(); 48 } 49 }); 50 51 $('.fileinput-remove').on('click',function () { 52 image = ''; 53 $("#topImg").val('').show().parent().show(); 54 $('.fileinput-upload').hide(); 55 })
六 我的例子:
js端
$('#input-b2').fileinput('destroy');
$("#input-b2").fileinput({
language: 'zh',
uploadUrl: '/' + namespace + '/a/alarmPrecept/alarmPrecept/public/fileupload',
showPreview:false,
showRemove: true,
showUpload: false,
showCancel: false,
showUploadedThumbs: false,
autoReplace: true,
maxFileCount:1,
mainClass: "",
browseClass:"btn btn-success"
});
var fileArray = $('#input-b2').fileinput('getFileStack'); if (fileArray.length > 0) { $('#input-b2').fileinput('upload'); $('#input-b2').on('fileuploaded', function(event, data, previewId, index) { if (data.response.status==2000) { $.ajax({ url: '/' + namespace + '/a/alarmPrecept/alarmPrecept/publish', type: 'POST', dataType: 'json', data: { c0919id: alarmPreceptId, precepttype: rowdata.precepttype, preceptname: rowdata.preceptname, startTime: startTime, endTime: endTime, filePath: data.response.filePath, importc0919id: alarmPrecept, preceptname: rowdata.preceptname }, success: function (result) { if (result.status == '4011') { dialog("error", result.message, 1000); return; } else { dialog("success", result.message, 1000); $('#preceptpublish-modal').modal('hide'); precept_table.ajax.reload(null, false); //重新加载数据 } }, error: function (result, status, xhr) { dialog("error", "发布失败", 1000); } }); } else { dialog("error", data.response.message, 1000); } }); }
html 端:
<div class="col-sm-12">
<div class="row">
<span class="col-sm-3 text-right" style="height: 34px;line-height: 34px;">
文件上传:
</span>
<div class="col-sm-9">
<div style="width: 100%">
<input id="input-b2" name="input-b2" type="file" class="file">
</div>
</div>
</div>
</div>
业务端:
@RequestMapping("fileuploadGXJ")
@ResponseBody
public Map<String, String> fileuploadGXJ(@RequestParam("input-b2") CommonsMultipartFile commonsMultipartFile,HttpServletRequest request){
Map<String, String> map = new HashMap<String,String>();
if(commonsMultipartFile.isEmpty()) {
map.put("status", "4011");
map.put("message", "文件为空,上传失败");
}
String filePath = Global.getConfig("fileinput");//参数1
String fileName = commonsMultipartFile.getOriginalFilename();//参数2
String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));//参数3
StringBuilder sBuilder = new StringBuilder();
sBuilder.append(filePath).append(File.separator).append(dateDir).append(File.separator).append(fileName);
System.out.println("上传信息 = "+sBuilder);
File file = new File(sBuilder.toString());
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try {
InputStream inputStream = commonsMultipartFile.getInputStream();
OutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024 * 1024];
int len = 0;
while((len = inputStream.read(buffer)) !=-1) {
out.write(buffer, 0, len);
}
out.close();
inputStream.close();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception ee) {
ee.printStackTrace();
}
map.put("status", "2000");
map.put("message", "上传成功");
map.put("filePath", sBuilder.toString());
return map;
}

浙公网安备 33010602011771号