Bootstrap之fileinput檔案上傳控制元件
前言~ 前段時間做專案用到了bootstrap裡中的檔案上傳控制元件,對此特定寫這篇文章,講述一下bootstrap的檔案上傳空間的使用方法。
我們進入正題吧!
首先bootstrap是基於jquery的,因此要匯入jquery響應jar包,可以找到以下網站:jquery相關js下載。
進入網址後,可以選擇我圈起來的地址,開啟瀏覽器輸入,並將該js的所有內容複製下來,建立一個" .js "檔案儲存這些內容作為jquery.js使用。
其次要下載bootstrap的檔案包,相必你們已經有了,那麼我就只推出下載fileinput的相關檔案包即可,以下是下載地址
再次分別匯入bootstrap和fileinput的相關css檔案,js檔案,如下所示:
<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引入。本人推薦使用第二種,因為比較靈活。下面我都列出兩種方式:
第一種:
<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>
第二種:
$(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:
屬性名 |
預設值 |
中文 |
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}" (<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} … |
載入第 {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 … |
拖拽檔案到這裡 …<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: '上傳 ...' }, |
7、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 |
|
在預覽框中圖片已經完全載入完畢後回撥的事件 |
後臺程式碼:
/**
* 多檔案上傳
* @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;
}