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


作項目用到bootstrap fileinput插件上傳文件,在用的過程當中,遇到一些問題,因此想着整理一份比較詳細的文檔,方便本身從此使用,也但願能給你們帶來幫助,若有錯誤,但願你們積極指正,積極交流。
注意:第三部份內容由於存在i標籤,某些文字被轉換成圖標php

1、引入文件

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

2、初始化設置

//初始化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);
});

3、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: '',next: '',toggleheader: '',fullscreen: '',borderless: '',close: ''},
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 ''
previewFileIconClass String 'file-other-icon'
previewFileIconSettings Object {}
previewFileExtSettings Object {}
buttonLabelClass String 'hidden-xs'
browseIcon String ' '
browseClass String 'btn btn-primary'
removeIcon String ''
removeClass String 'btn btn-default'
cancelIcon String ''
cancelClass String 'btn btn-default'
uploadIcon String ''
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 ' '
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 function 選擇後未上傳前 回調方法 null
dropZoneEnabled boolean 是否顯示拖拽區域 true
dropZoneTitleClass String 拖拽區域類屬性設置 'file-drop-zone-title'
fileActionSettings Object 設置預覽圖片的顯示樣式 {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 ...'}
otherActionButtons String ''
textEncoding String 編碼設置 'UTF-8'
ajaxSettings Object {}
ajaxDeleteSettings Object {}
showAjaxErrorDetails boolean true

4、提示說明設置

屬性名 默認值 中文
fileSingle file 文件
filePlural files 個文件
browseLabel Browse &hellip 選擇 …
removeLabel Remove 移除
removeTitle Clear selected files 清除選中文件
cancelLabel Cancel 取消
cancelTitle Abort ongoing upload 取消進行中的上傳
uploadLabel Upload 上傳
uploadTitle Upload selected files 上傳選中文件
msgNo No 沒有
msgNoFilesSelected No files selected 「」
msgCancelled Cancelled 取消
msgZoomModalHeading Detailed Preview 詳細預覽
msgSizeTooSmall File "{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.
msgSizeTooLarge File "{name}" ({size} KB) exceeds maximum allowed upload size of {maxSize} KB. 文件 "{name}" ({size} KB) 超過了容許大小 {maxSize} KB.
msgFilesTooLess You must select at least {n} {files} to upload. 你必須選擇最少 {n} {files} 來上傳.
msgFilesTooMany Number of files selected for upload ({n}) exceeds maximum allowed limit of {m}. 選擇的上傳文件個數 ({n}) 超出最大文件的限制個數 {m}.
msgFileNotFound File "{name}" not found! 文件 "{name}" 未找到!
msgFileSecured Security restrictions prevent reading the file "{name}". 安全限制,爲了防止讀取文件 "{name}".
msgFileNotReadable File "{name}" is not readable. 文件 "{name}" 不可讀.
msgFilePreviewAborted File preview aborted for "{name}". 取消 "{name}" 的預覽.
msgFilePreviewError An error occurred while reading the file "{name}". 讀取 "{name}" 時出現了一個錯誤.
msgInvalidFileName Invalid or unsupported characters in file name "{name}". Invalid or unsupported characters in file name "{name}".
msgInvalidFileType Invalid type for file "{name}". Only "{types}" files are supported. 不正確的類型 "{name}". 只支持 "{types}" 類型的文件.
msgInvalidFileExtension Invalid 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'},
msgUploadAborted The file upload was aborted 該文件上傳被停止
msgUploadThreshold Processing... Processing...
msgUploadBegin Initializing... Initializing...
msgUploadEnd Done Done
msgUploadEmpty No valid data available for upload. No valid data available for upload.
msgValidationError Validation Error 驗證錯誤
msgLoading Loading file {index} of {files} … 加載第 {index} 文件 共 {files} …
msgProgress Loading file {index} of {files} - {name} - {percent}% completed. 加載第 {index} 文件 共 {files} - {name} - {percent}% 完成.
msgSelected {n} {files} selected {n} {files} 選中
msgFoldersNotAllowed Drag & drop files only! {n} folder(s) dropped were skipped. 只支持拖拽文件! 跳過 {n} 拖拽的文件夾.
msgImageWidthSmall Width of image file "{name}" must be at least {size} px. 寬度的圖像文件的"{name}"的必須是至少{size}像素.
msgImageHeightSmall Height of image file "{name}" must be at least {size} px. 圖像文件的"{name}"的高度必須至少爲{size}像素.
msgImageWidthLarge Width of image file "{name}" cannot exceed {size} px. 寬度的圖像文件"{name}"不能超過{size}像素.
msgImageHeightLarge Height of image file "{name}" cannot exceed {size} px. 圖像文件"{name}"的高度不能超過{size}像素.
msgImageResizeError Could not get the image dimensions to resize. 沒法獲取的圖像尺寸調整。
msgImageResizeException Error while resizing the image.<pre>{errors}</pre> 錯誤而調整圖像大小。<pre>{errors}</pre>
msgAjaxError Something 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'},
dropZoneTitle Drag & 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: '上傳 ...'},

5、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 在預覽框中圖片已經徹底加載完畢後回調的事件
相關文章
相關標籤/搜索