一、 引入文件
<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>
二、 初始化设置:
$("#uploadfile").fileinput({
language: 'zh', //设置语言
uploadUrl:"http://127.0.0.1/testDemo/fileupload/upload.do", //上传的地址
allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
//uploadExtraData:{"id": 1, "fileName":'123.mp3'},
uploadAsync: true, //默认异步上传
showUpload:true, //是否显示上传按钮
showRemove :true, //显示移除按钮
showPreview :true, //是否显示预览
showCaption:false,//是否显示标题
browseClass:"btn btn-primary", //按钮样式
dropZoneEnabled: false,//是否显示拖拽区域
//minImageWidth: 50, //图片的最小宽度
//minImageHeight: 50,//图片的最小高度
//maxImageWidth: 1000,//图片的最大宽度
//maxImageHeight: 1000,//图片的最大高度
//maxFileSize:0,//单位为kb,如果为0表示不限制文件大小
//minFileCount: 0,
maxFileCount:10, //表示允许同时上传的最大文件个数
enctype:'multipart/form-data',
validateInitialCount:true,
previewFileIcon: "<iclass='glyphicon glyphicon-king'></i>",
msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
}).on("fileuploaded", function (event, data, previewId, index){
});
三、 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个文件,限制上传文件数。
备注:图片上传比例判断
$("#imgFile").fileinput({}).on('fileimageloaded',function(event,previewId){
var img = $('#'+previewId).find('img')[0];
if (img.naturalWidth!=img.naturalHeight) {
alert('图片尺寸必须1:1');
image_check = true;
$('.fileinput-remove').click();
}else{
image_check = false;
$('.fileinput-upload').show();
}
})
$("#imgFile").fileinput({
language : 'zh',
//uploadUrl:'../../module/uploadMod/index.php?c=upd&a=fileInputUpload&dir=image',
showUpload: false, //是否显示上传按钮
showCaption: false,//是否显示输入框
showRemove: true,//是否显示删除按钮
dropZoneEnabled: false,
showClose:false,
showDrag: false,
//initialPreviewShowDelete:false,
browseClass: "btn btn-primary",
allowedFileExtensions: ['jpg', 'png', 'gif'],
previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
overwriteInitial: false,
initialPreviewAsData: true,
//initialPreview: [],
//initialPreviewConfig:images_arr_info,
fileActionSettings:{
showZoom: true,
showDrag: false,
showRemove:false,
showUpload:false
}
}).on("fileuploaded", function(event, data,previewId,index) {
var data = data.response;
image = JSON.stringify(data);
$("#topImg").hide().parent().hide();
$('.fileinput-upload').hide();
}).on('filebatchselected', function(event, files) {
if(files.length<=0){
$('.fileinput-upload-button').hide();
}else{
$('.fileinput-upload-button').show();
}
}).on('fileimageloaded',function(event,previewId){
var img = $('#'+previewId).find('img')[0];
if (img.naturalWidth!=img.naturalHeight) {
alert('图片尺寸必须1:1');
image_check = true;
$('.fileinput-remove').click();
}else{
image_check = false;
$('.fileinput-upload').show();
}
});
$('.fileinput-remove').on('click',function () {
image = '';
$("#topImg").val('').show().parent().show();
$('.fileinput-upload').hide();
})
六 我的例子:
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;
}