Bootstrap FileInput(文件上传)中文API整理

下载地址、API和DOM地址(英语好的小伙伴可以看看)

下载地址:https://github.com/kartik-v/b…
API文档 :http://plugins.krajee.com/fil…
D E M O:http://plugins.krajee.com/fil…

做项目用到bootstrap fileinput插件上传文件,在用的过程中,遇到一些问题,所以想着整理一份比较详细的文档,方便自己今后使用,也希望能给大家带来帮助,如有错误,希望大家积极指正,积极交流。
注意:第三部分内容因为存在i标签,某些文字被转换成图标

一、引入文件

<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>

二、初始化设置

//初始化fileinput
initFileInput();
function initFileInput() {
    $("#uploadImg").fileinput({
        language: 'zh', //设置语言
        dropZoneTitle: '可以将图片拖放到这里 …支持多文件上传',
        uploadUrl: "index.php", //上传的地址
        uploadExtraData: function(previewId, index) {   //该插件可以向您的服务器方法发送附加数据。这可以通过uploadExtraData在键值对中设置为关联数组对象来完成。所以如果你有设置uploadExtraData={id:'kv-1'},在PHP中你可以读取这些数据$_POST['id']
            var id = $('#id').val();
            return {seriesId: id};
        },
        allowedFileExtensions: ['jpg','png'],//接收的文件后缀
        uploadAsync: true, //默认异步上传
        showUpload: true, //是否显示上传按钮
        showRemove: true, //显示移除按钮
        showPreview: true, //是否显示预览
        showCancel:true,   //是否显示文件上传取消按钮。默认为true。只有在AJAX上传过程中,才会启用和显示
        showCaption: true,//是否显示文件标题,默认为true
        browseClass: "btn btn-primary", //文件选择器/浏览按钮的CSS类。默认为btn btn-primary
        dropZoneEnabled: true,//是否显示拖拽区域
        minImageWidth: 50, //图片的最小宽度
        minImageHeight: 50,//图片的最小高度
        maxImageWidth: 1000,//图片的最大宽度
        maxImageHeight: 1000,//图片的最大高度
        maxFileSize: 1024,//单位为kb,如果为0表示不限制文件大小
        minFileCount: 1, //每次上传允许的最少文件数。如果设置为0,则表示文件数是可选的。默认为0
        maxFileCount: 0, //每次上传允许的最大文件数。如果设置为0,则表示允许的文件数是无限制的。默认为0
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",//当检测到用于预览的不可读文件类型时,将在每个预览文件缩略图中显示的图标。默认为<i class="glyphicon glyphicon-file"></i>  
        layoutTemplates:{
            actionUpload:''//去除上传预览缩略图中的上传图片
            actionZoom:'',   //去除上传预览缩略图中的查看详情预览的缩略图标
            actionDownload:'' //去除上传预览缩略图中的下载图标
            actionDelete:'', //去除上传预览的缩略图中的删除图标
        },//对象用于渲染布局的每个部分的模板配置。您可以设置以下模板来控制窗口小部件布局.eg:去除上传图标
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",//字符串,当文件数超过设置的最大计数时显示的消息 maxFileCount。默认为:选择上传的文件数({n})超出了允许的最大限制{m}。请重试您的上传!
    }).on('filebatchpreupload', function(event, data) { //该方法将在上传之前触发
        var id = $('#id option:selected').val();
        if(id == 0){
            return {
                message: "请选择", // 验证错误信息在上传前要显示。如果设置了这个设置,插件会在调用时自动中止上传,并将其显示为错误消息。您可以使用此属性来读取文件并执行自己的自定义验证
                data:{} // any other data to send that can be referred in `filecustomerror`
            };
        }
    });
}
//fileuploaded此事件仅针对ajax上传触发,并在每个缩略图文件上传完成后触发。此事件仅针对ajax上传并在以下情况下触发:当点击每个预览缩略图中的上传图标并且文件上传成功时,或者当你有 uploadAsync设置为true您已触发批量上传。在这种情况下,fileuploaded每一个人选择的文件被上传成功后,触发事件。
var id_str = '';
$('#uploadImg').on('fileuploaded', function(event, data, previewId, index) {
    if(typeof(data.response.id) != 'undefined'){
        id_str = id_str+data.response.id+',';
    }
});
// filebatchuploadcomplete此事件仅在ajax上传和完成同步或异步ajax批量上传后触发。
$('#uploadImg').on('filebatchuploadcomplete',function (event,files,extra) {
    if(id_str.length == 0){
        layer.msg('上传失败', {icon: 0});//弹框提示
        return false;
    }
    setTimeout(function(){ //执行延时关闭
        closeSelf();
    },1000);
});

三、Options 说明

属性名属性类型描述说明默认值
languageString多语言设置,使用时需提前引入locales文件夹下对应的语言文件,中文zh,引入语言文件必须放在fileinput.js之后‘en’
showCaptionBoolean是否显示被选文件的简介true
showBrowseBoolean是否显示浏览按钮true
showPreviewBoolean是否显示预览区域true
showRemoveBoolean是否显示移除按钮true,
showUploadBoolean是否显示上传按钮true,
showCancelBoolean是否显示取消按钮true,
showClose:Boolean是否显示关闭按钮true
showUploadedThumbsBooleantrue
browseOnZoneClickBooleanfalse
autoReplaceBoolean是否自动替换当前图片,设置为true时,再次选择文件, 会将当前的文件替换掉。false
generateFileIdObjectnull
previewClassString添加预览按钮的类属性‘’
captionClassString‘’
frameClassString‘krajee-default’
mainClassString‘file-caption-main’
mainTemplateObjectnull
purifyHtmlBooleantrue
fileSizeGetterObjectnull
initialCaptionString
initialPreviewArray/Object[]
initialPreviewDelimiterString$$
initialPreviewAsDataBooleanfalse
initialPreviewFileTypeString‘image’
initialPreviewConfigArray/Object[]
initialPreviewThumbTagsArray/Object[]
previewThumbTagsObject{}
initialPreviewShowDeleteBooleantrue
removeFromPreviewOnErrorBooleanfalse
deleteUrlString删除图片时的请求路径
deleteExtraDataObject删除图片时额外传入的参数{}
overwriteInitialBooleantrue
previewZoomButtonIconsObject{prev: ”,next: ”,toggleheader: ”,fullscreen: ”,borderless: ”,close: ”},
previewZoomButtonClassesObject{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’},
preferIconicPreviewBoolreanfalse
preferIconicZoomPreviewBoolreanfalse
allowedPreviewTypesundefinedundefined
allowedPreviewMimeTypesObjectnull
allowedFileTypesObject接收的文件后缀,如[‘jpg’, ‘gif’, ‘png’],不填将不限制上传文件后缀类型null
allowedFileExtensionsObjectnull
defaultPreviewContentObjectnull
customLayoutTagsObject{}
customPreviewTagsObject{}
previewFileIconString
previewFileIconClassString‘file-other-icon’
previewFileIconSettingsObject{}
previewFileExtSettingsObject{}
buttonLabelClassString‘hidden-xs’
browseIconString‘ ‘
browseClassString‘btn btn-primary’
removeIconString
removeClassString‘btn btn-default’
cancelIconString
cancelClassString‘btn btn-default’
uploadIconString
uploadClassString‘btn btn-default’
uploadUrlString上传文件路径null
uploadAsyncboolean是否为异步上传true
uploadExtraData上传文件时额外传递的参数设置{}
zoomModalHeightnumber480
minImageWidthString图片的最小宽度null
minImageHeightString图片的最小高度null
maxImageWidthString图片的最大宽度null
maxImageHeightString图片的最大高度null
resizeImagebooleanfalse
resizePreferenceString‘width’
resizeQualitynumber0.92
resizeDefaultImageTypeString‘image/jpeg’
minFileSizenumber单位为kb,上传文件的最小大小值0
maxFileSizenumber单位为kb,如果为0表示不限制文件大小0
resizeDefaultImageTypenumber25600(25MB)
minFileCountnumber表示同时最小上传的文件个数0
maxFileCountnumber表示允许同时上传的最大文件个数0
validateInitialCountbooleanfalse
msgValidationErrorClassString‘text-danger’
msgValidationErrorIconString‘ ‘
msgErrorClassString‘file-error-message’
progressThumbClassString“progress-bar progress-bar-success progress-bar-striped active”
rogressClassString“progress-bar progress-bar-success progress-bar-striped active”
progressCompleteClassString“progress-bar progress-bar-success”
progressErrorClassString“progress-bar progress-bar-danger”
progressUploadThresholdnumber99
previewFileTypeString预览文件类型,内置[‘image’, ‘html’, ‘text’, ‘video’, ‘audio’, ‘flash’, ‘object’,‘other‘]等格式‘image’
elCaptionContainerStringnull
elCaptionTextString设置标题栏提示信息null
elPreviewContainerStringnull
elPreviewImageStringnull
elPreviewStatusStringnull
elErrorContainerStringnull
errorCloseButtonString‘<span class=”close kv-error-close”>×</span>’
slugCallbackfunction选择后未上传前 回调方法null
dropZoneEnabledboolean是否显示拖拽区域true
dropZoneTitleClassString拖拽区域类属性设置‘file-drop-zone-title’
fileActionSettingsObject设置预览图片的显示样式{showRemove: true,showUpload: false,showZoom: true,showDrag: true,removeIcon: ”,removeClass: ‘btn btn-xs btn-default’,removeTitle: ‘Remove file’,uploadIcon: ”,uploadClass: ‘btn btn-xs btn-default’,uploadTitle: ‘Upload file’,zoomIcon: ”,zoomClass: ‘btn btn-xs btn-default’,zoomTitle: ‘View Details’,dragIcon: ”,dragClass: ‘text-info’,dragTitle: ‘Move / Rearrange’,dragSettings: {},indicatorNew: ”,indicatorSuccess: ”,indicatorError: ”,indicatorLoading: ”,indicatorNewTitle: ‘Not uploaded yet’,indicatorSuccessTitle: ‘Uploaded’,indicatorErrorTitle: ‘Upload Error’,indicatorLoadingTitle: ‘Uploading …’}
otherActionButtonsString
textEncodingString编码设置‘UTF-8’
ajaxSettingsObject{}
ajaxDeleteSettingsObject{}
showAjaxErrorDetailsbooleantrue

四、提示说明设置

属性名默认值中文
fileSinglefile文件
filePluralfiles个文件
browseLabelBrowse &hellip选择 …
removeLabelRemove移除
removeTitleClear selected files清除选中文件
cancelLabelCancel取消
cancelTitleAbort ongoing upload取消进行中的上传
uploadLabelUpload上传
uploadTitleUpload selected files上传选中文件
msgNoNo没有
msgNoFilesSelectedNo files selected“”
msgCancelledCancelled取消
msgZoomModalHeadingDetailed Preview详细预览
msgSizeTooSmallFile “{name}” ({size} KB) is too small and must be larger than {minSize} KB.File “{name}” ({size} KB) is too small and must be larger than {minSize} KB.
msgSizeTooLargeFile “{name}” ({size} KB) exceeds maximum allowed upload size of {maxSize} KB.文件 “{name}” ({size} KB) 超过了允许大小 {maxSize} KB.
msgFilesTooLessYou must select at least {n} {files} to upload.你必须选择最少 {n} {files} 来上传.
msgFilesTooManyNumber of files selected for upload ({n}) exceeds maximum allowed limit of {m}.选择的上传文件个数 ({n}) 超出最大文件的限制个数 {m}.
msgFileNotFoundFile “{name}” not found!文件 “{name}” 未找到!
msgFileSecuredSecurity restrictions prevent reading the file “{name}”.安全限制,为了防止读取文件 “{name}”.
msgFileNotReadableFile “{name}” is not readable.文件 “{name}” 不可读.
msgFilePreviewAbortedFile preview aborted for “{name}”.取消 “{name}” 的预览.
msgFilePreviewErrorAn error occurred while reading the file “{name}”.读取 “{name}” 时出现了一个错误.
msgInvalidFileNameInvalid or unsupported characters in file name “{name}”.Invalid or unsupported characters in file name “{name}”.
msgInvalidFileTypeInvalid type for file “{name}”. Only “{types}” files are supported.不正确的类型 “{name}”. 只支持 “{types}” 类型的文件.
msgInvalidFileExtensionInvalid extension for file “{name}”. Only “{extensions}” files are supported.不正确的文件扩展名 “{name}”. 只支持 “{extensions}” 的文件扩展名.
msgFileTypes{‘image’: ‘image’,’html’: ‘HTML’,’text’: ‘text’,’video’: ‘video’,’audio’: ‘audio’,’flash’: ‘flash’,’pdf’: ‘PDF’,’object’: ‘object’},{‘image’: ‘image’,’html’: ‘HTML’,’text’: ‘text’,’video’: ‘video’,’audio’: ‘audio’,’flash’: ‘flash’,’pdf’: ‘PDF’,’object’: ‘object’},
msgUploadAbortedThe file upload was aborted该文件上传被中止
msgUploadThresholdProcessing…Processing…
msgUploadBeginInitializing…Initializing…
msgUploadEndDoneDone
msgUploadEmptyNo valid data available for upload.No valid data available for upload.
msgValidationErrorValidation Error验证错误
msgLoadingLoading file {index} of {files} …加载第 {index} 文件 共 {files} …
msgProgressLoading file {index} of {files} – {name} – {percent}% completed.加载第 {index} 文件 共 {files} – {name} – {percent}% 完成.
msgSelected{n} {files} selected{n} {files} 选中
msgFoldersNotAllowedDrag & drop files only! {n} folder(s) dropped were skipped.只支持拖拽文件! 跳过 {n} 拖拽的文件夹.
msgImageWidthSmallWidth of image file “{name}” must be at least {size} px.宽度的图像文件的”{name}”的必须是至少{size}像素.
msgImageHeightSmallHeight of image file “{name}” must be at least {size} px.图像文件的”{name}”的高度必须至少为{size}像素.
msgImageWidthLargeWidth of image file “{name}” cannot exceed {size} px.宽度的图像文件”{name}”不能超过{size}像素.
msgImageHeightLargeHeight of image file “{name}” cannot exceed {size} px.图像文件”{name}”的高度不能超过{size}像素.
msgImageResizeErrorCould not get the image dimensions to resize.无法获取的图像尺寸调整。
msgImageResizeExceptionError while resizing the image.<pre>{errors}</pre>错误而调整图像大小。<pre>{errors}</pre>
msgAjaxErrorSomething went wrong with the {operation} operation. Please try again later!Something went wrong with the {operation} operation. Please try again later!
msgAjaxProgressError{operation} failed{operation} failed
ajaxOperations{deleteThumb: ‘file delete’, uploadThumb: ‘file upload’, uploadBatch: ‘batch file upload’, uploadExtra: ‘form data upload’ },{deleteThumb: ‘file delete’,uploadThumb: ‘file upload’, uploadBatch: ‘batch file upload’,uploadExtra: ‘form data upload’},
dropZoneTitleDrag & drop files here …拖拽文件到这里 …
支持多文件同时上传
dropZoneClickTitle(or click to select {files})(或点击{files}按钮选择文件)
previewZoomButtonTitles{prev: ‘View previous file’,next: ‘View next file’, toggleheader: ‘Toggle header’,fullscreen: ‘Toggle full screen’, borderless: ‘Toggle borderless mode’, close: ‘Close detailed preview’ }{ prev: ‘预览上一个文件’,next: ‘预览下一个文件’,toggleheader: ‘缩放’, fullscreen: ‘全屏’, borderless: ‘无边界模式’,close: ‘关闭当前预览’}
fileActionSettings{ removeTitle: ‘删除文件’,uploadTitle: ‘上传文件’,zoomTitle: ‘查看详情’,dragTitle: ‘移动 / 重置’,indicatorNewTitle: ‘没有上传’, indicatorSuccessTitle: ‘上传’,indicatorErrorTitle: ‘上传错误’, indicatorLoadingTitle: ‘上传 …’},

五、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”).on(“fileuploaded”, function(event, data, previewId, index) {});
filereset
fileclear点击浏览框右上角X 清空文件前响应事件$(“#fileinput”).on(“fileclear”,function(event, data, msg){});
filecleared点击浏览框右上角X 清空文件后响应事件$(“#fileinput”).on(“filecleared”,function(event, data, msg){});
fileimageuploaded在预览框中图片已经完全加载完毕后回调的事件
    原文作者:Ps1996
    原文地址: https://segmentfault.com/a/1190000018477200
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞