1. 程式人生 > >使用外掛Bootstrap Fileinput檔案上傳

使用外掛Bootstrap Fileinput檔案上傳

最近的專案中有用到這個外掛,覺得功能挺強大的。

GitHub地址:https://github.com/kartik-v/bootstrap-fileinput/

git地址:https://github.com/kartik-v/bootstrap-fileinput.git

類似的效果如下圖:

一、載入

需要載入樣式:

<link href="${pageContext.request.contextPath}/plug-in/bootstrap-fileinput-master/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css" />
        <link href="${pageContext.request.contextPath}/plug-in/bootstrap-fileinput-master/themes/explorer/theme.css" media="all" rel="stylesheet" type="text/css"/>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">

以及js:

<script type="text/javascript" src="${pageContext.request.contextPath}/assets/js/jquery-2.0.3.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>

<script src="${pageContext.request.contextPath}/plug-in/bootstrap-fileinput-master/js/fileinput.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/plug-in/bootstrap-fileinput-master/js/plugins/sortable.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/plug-in/bootstrap-fileinput-master/themes/explorer/theme.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/plug-in/bootstrap-fileinput-master/js/locales/zh.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>&nbsp;'

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">&times;</span>'

slugCallback

String

null

dropZoneEnabled

boolean

是否顯示拖拽區域

true

dropZoneTitleClass

String

拖拽區域類屬性設定

'file-drop-zone-title'

fileActionSettings

Object

設定預覽圖片的顯示樣式

{

    showRemove: true,

    showUpload: false,

    showZoom: true,

    showDrag: true,

    removeIcon: '<i class="glyphicon glyphicon-trash text-danger"></i>',

    removeClass: 'btn btn-xs btn-default',

    removeTitle: 'Remove file',

    uploadIcon: '<i class="glyphicon glyphicon-upload text-info"></i>',

    uploadClass: 'btn btn-xs btn-default',

    uploadTitle: 'Upload file',

    zoomIcon: '<i class="glyphicon glyphicon-zoom-in"></i>',

    zoomClass: 'btn btn-xs btn-default',

    zoomTitle: 'View Details',

    dragIcon: '<i class="glyphicon glyphicon-menu-hamburger"></i>',

    dragClass: 'text-info',

    dragTitle: 'Move / Rearrange',

    dragSettings: {},

    indicatorNew: '<i class="glyphicon glyphicon-hand-down text-warning"></i>',

    indicatorSuccess: '<i class="glyphicon glyphicon-ok-sign text-success"></i>',

    indicatorError: '<i class="glyphicon glyphicon-exclamation-sign text-danger"></i>',

    indicatorLoading: '<i class="glyphicon glyphicon-hand-up text-muted"></i>',

    indicatorNewTitle: 'Not uploaded yet',

    indicatorSuccessTitle: 'Uploaded',

    indicatorErrorTitle: 'Upload Error',

    indicatorLoadingTitle: 'Uploading ...'

}

otherActionButtons

String

''

textEncoding

String

編碼設定

'UTF-8'

ajaxSettings

Object

{}

ajaxDeleteSettings

Object

{}

showAjaxErrorDetails

boolean

true


四、    提示說明設定:

屬性名

預設值

中文

fileSingle

file

檔案

filePlural

files

個檔案

browseLabel

Browse &hellip

選擇 &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}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.

File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.

msgSizeTooLarge

File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.

檔案 "{name}" (<b>{size} KB</b>) 超過了允許大小 <b>{maxSize} KB</b>.

msgFilesTooLess

You must select at least <b>{n}</b> {files} to upload.

你必須選擇最少 <b>{n}</b> {files} 來上傳.

msgFilesTooMany

Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.

選擇的上傳檔案個數 <b>({n})</b> 超出最大檔案的限制個數 <b>{m}</b>.

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} &hellip;

載入第 {index} 檔案 共 {files} &hellip;

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 &hellip;

拖拽檔案到這裡 &hellip;<br>支援多檔案同時上傳

dropZoneClickTitle

<br>(or click to select {files})

<br>(或點選{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

在預覽框中圖片已經完全載入完畢後回撥的事件

六、    常見錯誤:

 (1)   當點選上傳後,報錯,提示你必須選擇最少X個檔案上傳。

錯誤原因:html中input標籤元素屬性:data-min-file-count="2" 設定為X個檔案,限制上傳檔案數。