============= boostrap-fileinput 使用總結: =========
1.引入css文件:
<link rel="stylesheet" href="${ctx}/resources/lib/bootstrap/css/fileinput.min.css"/>
2.引入js文件:
<script src="${ctx}/resources/lib/jquery/js/jquery-3.1.1.min.js"></script>
<script src="${ctx}/resources/lib/bootstrap/js/bootstrap.min.js"></script>
<script src="${ctx}/resources/lib/bootstrap/js/fileinput.min.js"></script>
<script src="${ctx}/resources/lib/bootstrap/js/locales/zh.js"></script>
<script src="${ctx}/resources/lib/bootstrap/js/plugins/piexif.js"></script>
3.加入html元素:
<input id="imageScriptFile" name="imageScriptFile" type="file" multiple>
若是是隻讀,則設置readonly;若是是單個文件,則去掉multiple 屬性
4.初始化說明:
4.1.初始化上傳控件的樣式
$(#fileInputId).fileinput(file_config)
4.1.刪除文件有2個事件(區別):
//刪除新上傳的文件
$(#fileInputId).on("filesuccessremove", function (event, previewId) {})
//刪除回顯的文件,默認採用POST方式提交
$(#fileInputId).on('filedeleted', function (event, key, json, params) {})
5.文件參考:
fileinput.jsp + fileinput.javajavascript
fileinput.jsp以下:css
1 <script type="text/javascript"> 2 3 var file_count = 0;//用於統計上傳的文件數量 4 var scriptArr = new Array();//用於反選文件 5 var delete_fileIds = new Array();//用於存儲刪除的文件id集合 6 $(function () { 7 initArray();//初始化反選的文件列表 8 initFileInput("imageScriptFile", "/imageEvaluateScript/upload.do", scriptArr, 10); 9 }); 10 11 function initFileInput(ctrlName, uploadUrl, initValue, fileCount) { 12 var control = $('#' + ctrlName) 13 var file_config = { 14 language: 'zh', //設置語言 15 // uploadUrl: 'http://127.0.0.1/testDemo/fileupload/upload.action', //上傳的地址,不設置則採用表單提交 16 uploadUrl: CONTEXT_PATH + uploadUrl, //上傳的地址 17 allowedFileExtensions: [], //接收的文件後綴,如['jpg', 'png', 'gif'] 18 uploadAsync: false, //默認異步上傳 19 showUpload: false, //是否顯示上傳按鈕 20 showRemove: false, //顯示移除按鈕 21 showCaption: true, //是否顯示標題 22 showPreview: true, //是否顯示預覽 23 dropZoneEnabled: true, //是否顯示拖拽區域 24 overwriteInitial: false, 25 // initialPreview: [initValue],//用於初始化文件列表 26 maxFileSize: 0,//單位爲kb,若是爲0表示不限制文件大小 27 minFileCount: 1, 28 maxFileCount: fileCount, //表示容許同時上傳的最大文件個數 29 enctype: 'multipart/form-data', 30 browseClass: 'btn btn-primary', //按鈕樣式: btn-default、btn-primary、btn-danger、btn-info、btn-warning 31 previewFileIcon: '<i class=\'glyphicon glyphicon-king\'></i>', 32 uploadExtraData: function () {//上傳參數 33 return {'name': $("#name").val(), "versionNum": $("#versionNum").val()}; 34 }, 35 //配置下面,纔會觸發刪除事件(filedeleted) 36 /* initialPreviewConfig: [{ 37 caption: 'desert.jpg',// 展現的圖片名稱 38 width: '120px',// 圖片高度 39 url: "",// 預展現圖片的刪除調取路徑 40 key: 0,// 可修改 場景2中會用的 41 extra: {id: 0} //調用刪除路徑所傳參數 42 }],*/ 43 } 44 45 var _initialPreview = []; 46 var _initialPreviewConfig = []; 47 initValue.forEach(function (it, index) { 48 _initialPreview.push(it.url) //[initValue] 49 _initialPreviewConfig.push({ 50 url: CONTEXT_PATH + "/image/delete/oldfile.do",//必需有,不然不能觸發 刪除事件(filedeleted) 51 key: it.fileName, 52 extra: {id: it.id, fileKey: it.fileKey, fileName: it.fileName}//配置刪除事件的參數(filedeleted) 53 }) 54 }) 55 file_config.initialPreview = _initialPreview 56 file_config.initialPreviewConfig = _initialPreviewConfig 57 if (ctrlName == 'imageScriptFile') { 58 file_config.allowedFileExtensions.push('sh');//設置上傳的文件類型 59 } 60 61 //初始化上傳控件的樣式 62 control.fileinput(file_config) 63 64 control.on('fileuploaded', function (event, data, previewId, index) { 65 if (data.response.flag) { 66 var fileKey = data.response.fileKey;//這個fileKey用於刪除的時候,後臺刪除臨時文件 67 // var json = jQuery.parseJSON(data.response.result) 68 $("#" + previewId).attr("data-fileKey", fileKey); 69 if (ctrlName == 'imageScriptFile') { 70 file_count_script++; 71 $("#imageSubmitBtn").removeAttr("disabled"); 72 } 73 } else { 74 dialogCollection.dialogWarns({ 75 text: "上傳錯誤,請刪除後,從新上傳" 76 }); 77 return false; 78 } 79 }) 80 //刪除新上傳的文件 81 control.on("filesuccessremove", function (event, previewId) { 82 var fileKey = $("#" + previewId).attr("data-fileKey"); 83 $.ajax({ 84 url: CONTEXT_PATH + "/image/delete/newfile.do", 85 data: {fileName: ctrlName + "s", fileKey: fileKey}, 86 type: "POST", 87 success: function () { 88 if (ctrlName == 'imageScriptFile') { 89 file_count_script--; 90 } 91 } 92 }); 93 }) 94 //刪除回顯的文件 95 control.on('filedeleted', function (event, key, json, params) { 96 //主要用到key和params2個參數,其中KEY在上面定義,而PARAMS是定義刪除事件中的參數,JSON爲上傳對象 97 console.log('Key = ', key); 98 console.log('params = ', params); 99 if (params.fileName == "imageScriptFiles") { 100 script_delete_ids.push(params.id) 101 file_count_script--; 102 } 103 }); 104 105 106 } 107 108 function initArray() { 109 <c:forEach items="${response.scriptFileList}" var="item" varStatus="status" > 110 scriptArr.push({ 111 url: "<div class='file-preview-text'>" + 112 "<h3><i class='glyphicon glyphicon-file'></i></h3>" + 113 "${item.fileName}" + "</div>", 114 id: Number("${item.id}"), 115 fileKey: "${item.fileKey}", 116 fileName: "imageScriptFiles" 117 }); 118 file_count_script++; 119 </c:forEach> 120 } 121 </script>
fileinput.java:html
1 刪除代碼以下: 2 3 //由於在提交的時候才刪除,記錄刪除的ID,這裏不作操做 4 @RequestMapping(value = "/delete/oldfile.do", method = {RequestMethod.POST}) 5 @ResponseBody 6 public Map deleteOldFileResponse() { 7 Map map = new HashMap<>(); 8 map.put("flag", true); 9 map.put("message", "刪除成功"); 10 return map; 11 } 12 13 @RequestMapping(value = "/delete/newfile.do", method = {RequestMethod.POST}) 14 @ResponseBody 15 public Map deleteNewFileResponse(HttpSession session, String fileName, String fileKey) { 16 Map map = new HashMap<>(); 17 map.put("flag", true); 18 map.put("message", "刪除成功"); 19 List<FileCacheInfo> list;//fileName imageScriptFiles imageAdditionFiles 20 Object obj = session.getAttribute(fileName); 21 if (obj == null) { 22 map.put("flag", false); 23 map.put("message", "刪除失敗,評測文件不存在"); 24 return map; 25 } else { 26 list = (List<FileCacheInfo>) obj; 27 for (FileCacheInfo fileCacheInfo : list) { 28 if (fileCacheInfo.getKey().equals(fileKey)) { 29 list.remove(fileCacheInfo); 30 session.setAttribute(fileName,list); 31 return map; 32 } 33 } 34 } 35 return map; 36 } 37 38 39 @RequestMapping(value = "/upload.do", method = {RequestMethod.POST}) 40 // @ResourcePermissions(name = "上傳鏡像腳本文件", value = "uploadImageEvaluateScript") 41 @ResponseBody 42 @DontWrap 43 public Map uploadScript(HttpServletRequest request){ 44 HttpSession session = request.getSession(); 45 MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; 46 MultipartFile file = multipartHttpServletRequest.getFile("imageScriptFile"); 47 if (file == null) { 48 throw new ToffException("請選擇文件"); 49 } 50 FileCacheInfo fileCacheInfo; 51 Map map = new HashMap<String,Object>(); 52 String fileCompleteName = file.getOriginalFilename(); 53 String fileName = fileCompleteName.substring(0, fileCompleteName.lastIndexOf(".")); 54 String fileExt = fileCompleteName.substring(fileCompleteName.lastIndexOf(".") + 1); 55 List<FileCacheInfo> list; 56 Object obj = session.getAttribute("imageScriptFiles"); 57 if (obj == null) { 58 list = new ArrayList<>(); 59 } else { 60 list = (List<FileCacheInfo>) obj; 61 } 62 try { 63 fileCacheInfo = imageEvaluateScriptService.getFileCacheInfo(null, fileName, fileExt, file.getInputStream(), file.getSize()); 64 } catch (IOException e) { 65 map.put("error", "上傳失敗"); 66 map.put("flag", false); 67 e.printStackTrace(); 68 return map; 69 } 70 FileCacheInfo tempFile = fileCacheService.saveTempFile(fileCacheInfo, null); 71 list.add(tempFile); 72 session.setAttribute("imageScriptFiles", list); 73 map.put("flag", true); 74 map.put("fileKey", tempFile.getKey()); 75 return map; 76 }