Bootstrap之fileinput文件上傳控件

 前言~ 前段時間作項目用到了bootstrap裏中的文件上傳控件,對此特定寫這篇文章,講述一下bootstrap的文件上傳空間的使用方法。javascript

咱們進入正題吧!css

       首先bootstrap是基於jquery的,所以要導入jquery響應jar包,能夠找到如下網站:jquery相關js下載html

進入網址後,能夠選擇我圈起來的地址,打開瀏覽器輸入,並將該js的全部內容複製下來,建立一個" .js "文件存儲這些內容做爲jquery.js使用。java

       其次要下載bootstrap的文件包,相必大家已經有了,那麼我就只推出下載fileinput的相關文件包便可,如下是下載地址下載fileinput相關文件包jquery

       再次分別導入bootstrap和fileinput的相關css文件,js文件,以下所示:git

<link rel="stylesheet" href="../static/css/bootstrap.css">

<link rel="stylesheet" href="../static/css/fileinput.min.css">

<link rel="stylesheet" href="../static/css/themes/theme.css">

<script type="text/javascript" src="../static/js/jquery-3.3.1.min.js"></script>

<script type="text/javascript" src="../static/js/fileinput.min.js"></script>

<script type="text/javascript" src="../static/js/locales/zh.js"></script>

<script type="text/javascript" src="../static/js/themes/theme.js"></script>

       後面能夠選擇兩種方式配置fileinput的相關屬性,一種是在jsp或者html中直接配置,第二種是寫一個js,而後將該js引入。本人推薦使用第二種,由於比較靈活。下面我都列出兩種方式:github

      第一種:ajax

<div class="container kv-main">

<div class="row ">

<div style="margin:100px 240px;width:700px;height:300px ">

<form nctype="multipart/form-data">

<input id="file-0a" class="file" name="file" type="file" multiple data-min-file-count="1">

<br>

</form>

</div>

</div>



<script>

$('#file-0a').fileinput({

'theme':'explorer',

language:'zh',

uploadUrl:'<%=path%>/uploadMultipleFile.do',

showPreview:true,//是否顯示預覽

    allowedPreviewTypes : ['image','html','text','video','audio','flash'],

maxFileCount :3,// 表示容許同時上傳的最大文件個數

});

$('#file-0a').on('fileuploaderror',function(event, data, previewId, index) {

var form = data.form,files = data.files,extra = data.extra,

response = data.response,reader = data.reader;

console.log(data);

console.log('File upload error');

});

$('#file-0a').on('fileerror',function(event, data) {

console.log(data.id);

console.log(data.index);

console.log(data.file);

console.log(data.reader);

console.log(data.files);

});

$('#file-0a').on('fileuploaded',function(event, data, previewId, index) {

var form = data.form,files = data.files,extra = data.extra,

response = data.response,reader = data.reader;

console.log('File uploaded triggered');

});

</script>

第二種:json

$(function () {

    //0.初始化fileinputvaroFileInput =new FileInput();

    oFileInput.Init("file-0a", "/api/OrderApi/ImportOrder");

});

//初始化fileinputvarFileInput =function () {

    varoFile =new Object();

    //初始化fileinput控件(第一次初始化)oFile.Init =function(ctrlName, uploadUrl) {

    varcontrol = $('#' + ctrlName);

    //初始化上傳控件的樣式    control.fileinput({

        language: 'zh',//設置語言

        uploadUrl: uploadUrl,//上傳的地址

        allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件後綴

        showUpload: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: "",

        msgFilesTooMany: "選擇上傳的文件數量({n}) 超過容許的最大數值{m}!",    });

    //導入文件上傳完成以後的事件

$('#file-0a').on('fileuploaderror',function(event, data, previewId, index) {

var form = data.form,files = data.files,extra = data.extra,

response = data.response,reader = data.reader;

console.log(data);

console.log('File upload error');

});

$('#file-0a').on('fileerror',function(event, data) {

console.log(data.id);

console.log(data.index);

console.log(data.file);

console.log(data.reader);

console.log(data.files);

});

$('#file-0a').on('fileuploaded',function(event, data, previewId, index) {

var form = data.form,files = data.files,extra = data.extra,

response = data.response,reader = data.reader;

console.log('File uploaded triggered');

});

}

    return oFile;

};

如下將提供fileinput的相關api:bootstrap

屬性名

默認值

中文

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

 

在預覽框中圖片已經徹底加載完畢後回調的事件

 後臺代碼:

/**

* 多文件上傳

* @param files 文件數組

* @param request

* @return

* @throws IOException

*/

@RequestMapping(value ="/uploadMultipleFile.do", method = RequestMethod.POST, produces ="application/json;charset=utf8")

@ResponseBody

public Message uploadMultipleFileHandler(@RequestParam("file") MultipartFile[] files, HttpServletRequest request)throws IOException {

Message msg =new Message();

ArrayList arr =new ArrayList();

String serverPath=null;

for (int i =0; i < files.length; i++) {

MultipartFile file = files[i];

if (!file.isEmpty()) {

InputStream in =null;

OutputStream out =null;

try {

if(file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf(".")).contains("表1-惡意程序監測統計")){

serverPath=FileUtil.getMalwareUploadDirFilePath(file.getOriginalFilename(), request);

}else{

serverPath=FileUtil.getHighRiskUploadDirFilePath(file.getOriginalFilename(), request);

}

/*String serverPath=dir.getAbsolutePath() + File.separator + file.getOriginalFilename();*/

                File serverFile =new File(serverPath);

in = file.getInputStream();

out =new FileOutputStream(serverFile);

byte[] b =new byte[1024];

int len =0;

while ((len = in.read(b)) >0) {

out.write(b,0, len);

}

out.close();

in.close();

logger.info("Server File Location=" + serverFile.getAbsolutePath());

}catch (Exception e) {

arr.add(i);

}finally {

if (out !=null) {

out.close();

out =null;

}

if (in !=null) {

in.close();

in =null;

}

}

}else {

arr.add(i);

}

}

if(arr.size() >0) {

msg.setStatus(Status.ERROR);

msg.setError("Files upload fail");

msg.setErrorKys(arr);

}else {

msg.setStatus(Status.SUCCESS);

msg.setStatusMsg("Files upload success");

}

return msg;

}
相關文章
相關標籤/搜索