fileinput
============= 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.java
fileinput.jsp如下:
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:
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 }