Bootstrap中的fileinput 多圖片上傳及編輯功能
大家如果對Bootstrap-fileinput 的配置不清楚的話,大家可以查看官方網(wǎng)站:http://plugins.krajee.com/file-input。
邏輯說明:先從后臺獲取數(shù)據(jù)展示,然后進(jìn)行編輯。
廢話不多說, 直接上代碼.
1. 頁面部分代碼:
<div class="form-group"> <label for="inputEmail3" class="col-xs-3 control-label">項(xiàng)目LOGO</label> <div class="col-xs-7"> <input id="testlogo" type="file" name="icoFile" class="file-loading" /> <input type="text" name="htestlogo" id="htestlogo" onchange="addFile(this)" > </div> </div>
說明: 其中onchange()為我業(yè)務(wù)需要, 上傳完成后自動執(zhí)行一個(gè)添加事件。 此方法可以去掉。
2. 獲取初始化數(shù)據(jù)方法:
// 初始化獲取原有文件 $(function(){ $.ajax({ type : "post", url : "/eim/project/testFileUpload.do", dataType : "json", success : function(data) { layer.msg('操作成功!'); showPhotos(data); }, error: function(XMLHttpRequest, textStatus, errorThrown) { layer.msg('操作失?。?); } }); });
說明:此處我返回是一個(gè) 對象數(shù)組:List<MemberUser>,可以理解為獲取一個(gè)班中所有的學(xué)生,展示頭像
3.初始化bootstrap-fileinput 組件:
function showPhotos(djson){ //后臺返回json字符串轉(zhuǎn)換為json對象 var reData = eval(djson); // 預(yù)覽圖片json數(shù)據(jù)組 var preList = new Array(); for ( var i = 0; i < reData.length; i++) { var array_element = reData[i]; // 此處指針對.txt判斷,其余自行添加 if(array_element.fileIdFile.name.indexOf("txt")>0){ // 非圖片類型的展示 preList[i]= "<div class='file-preview-other-frame'><div class='file-preview-other'><span class='file-icon-4x'><i class='fa fa-file-text-o text-info'></i></span></div></div>" }else{ // 圖片類型 preList[i]= "<img src=\"/eim/upload/getIMG.do?savePath="+array_element.fileIdFile.filePath+"&name="+array_element.fileIdFile.name+"\" class=\"file-preview-image\">"; } } var previewJson = preList; // 與上面 預(yù)覽圖片json數(shù)據(jù)組 對應(yīng)的config數(shù)據(jù) var preConfigList = new Array(); for ( var i = 0; i < reData.length; i++) { var array_element = reData[i]; var tjson = {caption: array_element.fileIdFile.fileName, // 展示的文件名 width: '120px', url: '/eim/project/deleteFile.do', // 刪除url key: array_element.id, // 刪除是Ajax向后臺傳遞的參數(shù) extra: {id: 100} }; preConfigList[i] = tjson; } // 具體參數(shù)自行查詢 $('#testlogo').fileinput({ uploadUrl: '/eim/upload/uploadFile.do', uploadAsync:true, showCaption: true, showUpload: true,//是否顯示上傳按鈕 showRemove: false,//是否顯示刪除按鈕 showCaption: true,//是否顯示輸入框 showPreview:true, showCancel:true, dropZoneEnabled: false, maxFileCount: 10, initialPreviewShowDelete:true, msgFilesTooMany: "選擇上傳的文件數(shù)量 超過允許的最大數(shù)值!", initialPreview: previewJson, previewFileIcon: '<i class="fa fa-file"></i>', allowedPreviewTypes: ['image'], previewFileIconSettings: { 'docx': '<i class="fa fa-file-word-o text-primary"></i>', 'xlsx': '<i class="fa fa-file-excel-o text-success"></i>', 'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>', 'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>', 'zip': '<i class="fa fa-file-archive-o text-muted"></i>', 'sql': '<i class="fa fa-file-word-o text-primary"></i>', }, initialPreviewConfig: preConfigList }).off('filepreupload').on('filepreupload', function() { // alert(data.url); }).on("fileuploaded", function(event, outData) { //文件上傳成功后返回的數(shù)據(jù), 此處我只保存返回文件的id var result = outData.response.id; // 對應(yīng)的input 賦值 $('#htestlogo').val(result).change(); }); }
4. 后臺java保存文件部分代碼
@RequestMapping(value="/uploadFile",method=RequestMethod.POST) @ResponseBody public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //轉(zhuǎn)型為MultipartHttpServletRequest MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request; //獲取文件到map容器中 Map<String,MultipartFile> fileMap = multipartRequest.getFileMap(); //獲取頁面?zhèn)鬟f過來的路徑參數(shù) folderPath = request.getParameter("folder"); String rootPath = BaseConfig.uploadPath; String filePath = rootPath + folderPath+"/"; //文件上傳并返回map容器,map存儲了文件信息 FileModel fileModel = UploadifyUtils.uploadFiles(filePath,fileMap); boolean flag = service.add(fileModel); if(flag){ String result = fileModel.getId()+";"+fileModel.getFilePath()+";"+fileModel.getName()+";"+fileModel.getFilePath(); Map map = new HashMap<>(); map.put("id", fileModel.getId()); //返回文件保存ID //response.getWriter().write(map); return map; } return null; }
說明:該段代碼為獲取上傳文件的部分信息, 如文件名,上傳的路徑 等,將文件信息保存到表中,對應(yīng)對象為 FileModel 。
5.上傳完成后重新刷新該組件即可。
最終展示效果 :
說明:此處指針對txt文件類型判斷, 其余的doc,ppt里面有對應(yīng)的展示圖標(biāo),只須在判斷是添加對應(yīng)樣式即可
附:根據(jù)路徑過去/下載文件代碼:
/** * 文件下載 * * @param savePath * 保存目錄 * @param name * 文件原名 * @param file * 保存時(shí)的名稱 包含后綴 * @param request * @param response * @return */ public static String down(String savePath, String name, String fileName, HttpServletRequest request, HttpServletResponse response) { try { String path = savePath + "/" + name; File file = new File(path); if (!file.exists()) { // 不存在 request.setAttribute("name", fileName); return "download_error";// 返回下載文件不存在 } response.setContentType("application/octet-stream"); // 根據(jù)不同瀏覽器 設(shè)置response的Header String userAgent = request.getHeader("User-Agent").toLowerCase(); if (userAgent.indexOf("msie") != -1) { // ie瀏覽器 // System.out.println("ie瀏覽器"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8")); } else { response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("utf-8"), "ISO8859-1")); } response.addHeader("Content-Length", "" + file.length()); // 以流的形式下載文件 InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); //response.setContentType("image/*"); // 設(shè)置返回的文件類型 OutputStream toClient = response.getOutputStream(); OutputStream bos = new BufferedOutputStream(toClient); //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(bos)); bos.write(buffer); //bw.close(); bos.close(); toClient.close(); return null; } catch (Exception e) { e.printStackTrace(); //response.reset(); return "exception";// 返回異常頁面 } finally { /* if (toClient != null) { try { toClient.close(); } catch (IOException e) { e.printStackTrace(); } }*/ } }
附:
UploadifyUtils.uploadFiles 部分代碼
public static FileModel uploadFiles(String savePath,Map<String,MultipartFile> fiLeMap){ //上傳文件 //附件模型對象 FileModel fm=new FileModel(); try { File file = new File(savePath); //判斷文件夾是否存在,如果不存在則創(chuàng)建文件夾 makeDir(file); if(fiLeMap!=null){ for(Map.Entry<String, MultipartFile> entity:fiLeMap.entrySet()){ MultipartFile f = entity.getValue(); if(f!=null&&!f.isEmpty()){ String uuid=UploadifyUtils.getUUID();//uuid作為保存時(shí)的文件名 String ext=UploadifyUtils.getFileExt(f.getOriginalFilename());//獲取文件后綴 //保存文件 File newFile = new File(savePath+"/"+uuid+"."+ext); f.transferTo(newFile); fm.setFileName(f.getOriginalFilename()); fm.setName(uuid+"."+ext); fm.setFilePath(savePath);//保存路徑 fm.setExt(ext); fm.setSize(f.getSize()); } } } return fm; }catch (Exception e) { log.error(e); return null; } }
以上所述是小編給大家介紹的Bootstrap中的fileinput 多圖片上傳編輯,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- Bootstrap Fileinput文件上傳組件用法詳解
- JS文件上傳神器bootstrap fileinput詳解
- Bootstrap fileinput文件上傳預(yù)覽插件使用詳解
- Bootstrap的fileinput插件實(shí)現(xiàn)多文件上傳的方法
- bootstrapfileinput實(shí)現(xiàn)文件自動上傳
- 基于bootstrap的上傳插件fileinput實(shí)現(xiàn)ajax異步上傳功能(支持多文件上傳預(yù)覽拖拽)
- 詳解bootstrap-fileinput文件上傳控件的親身實(shí)踐
- Bootstrap fileinput 上傳新文件移除時(shí)觸發(fā)服務(wù)器同步刪除的配置
- BootStrap fileinput.js文件上傳組件實(shí)例代碼
- Bootstrap FileInput實(shí)現(xiàn)圖片上傳功能
相關(guān)文章
小程序websocket心跳庫(websocket-heartbeat-miniprogram)
這篇文章主要介紹了小程序websocket心跳庫(websocket-heartbeat-miniprogram),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02基于JavaScript實(shí)現(xiàn)本地圖片預(yù)覽
這篇文章主要為大家詳細(xì)介紹了基于JavaScript實(shí)現(xiàn)本地圖片預(yù)覽的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02JavaScript中${pageContext.request.contextPath}取值問題及解決方案
這篇文章主要介紹了JavaScript中${pageContext.request.contextPath}取值問題及解決方案的相關(guān)資料,需要的朋友可以參考下2016-12-12js中調(diào)用微信的掃描二維碼功能的實(shí)現(xiàn)代碼
這篇文章主要介紹了在js中調(diào)用微信的掃描二維碼功能的實(shí)現(xiàn)代碼,本文給大家分享了注意事項(xiàng)及常見問題分析,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04