檔案上傳控制元件fileinput
需求:當上傳的檔案型別為word或者pdf的時候,直接顯示檔案的icon;為圖片的時候就是圖片內容的預覽。
需要的檔案依賴:
<script src="js/fileinput.min.js"></script>
<script src="js/fileinput_zh.js"></script>
<link rel="stylesheet" type="text/css" href="css/fileinput.min.css">
引入檔案的過程就不多說了,主要說下這個需求的實現:
fileinput裡面的主要方法有:
方法名 |
引數 |
描述 |
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 |
在預覽框中圖片已經完全載入完畢後回撥的事件 |
所以要實現如果點選的是word或者pdf,上面顯示的是檔案型別的icon這個需求,應該寫在選擇檔案之後點選確定之前操作的事件裡面,也就是filebatchselected,主要程式碼為:
.on("filebatchselected", function(event, files) {//選擇檔案後處理事件
var imgContent = $(event.target).parents(".file-input").find(".file-preview-frame");//顯示內容的容器
var fileType = files[0].name.split('.')[1];//檔案型別
if(fileType =='pdf'){
imgContent.html('<img src="../../../include/images/pdf.png" />');
}else if(fileType =='doc' || fileType =='docx'){
imgContent.html('<img src="../../../include/images/word.png" />');
}
})
event:檔案上傳選擇框的有關資訊
files:上傳的檔案的有關資訊