Bootstrap中的fileinput 多圖片上傳及編輯功能,

來源:互聯網
上載者:User

Bootstrap中的fileinput 多圖片上傳及編輯功能,

大家如果對Bootstrap-fileinput 的配置不清楚的話,大家可以查看官方網站:http://plugins.krajee.com/file-input。

邏輯說明:先從後台擷取資料展示,然後進行編輯。

廢話不多說, 直接上代碼.

1. 頁面部分代碼:

<div class="form-group"> <label for="inputEmail3" class="col-xs-3 control-label">項目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()為我業務需要, 上傳完成後自動執行一個添加事件。 此方法可以去掉。

2. 擷取初始化資料方法:

// 初始化擷取原有檔案 $(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('操作失敗!'); } }); }); 

說明:此處我返回是一個 對象數組:List<MemberUser>,可以理解為擷取一個班中所有的學生,展示頭像

3.初始化bootstrap-fileinput 組件:

function showPhotos(djson){ //後台返回json字串轉換為json對象 var reData = eval(djson); // 預覽圖片json資料群組 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; // 與上面 預覽圖片json資料群組 對應的config資料 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向後台傳遞的參數 extra: {id: 100} }; preConfigList[i] = tjson; } // 具體參數自行查詢 $('#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: "選擇上傳的檔案數量 超過允許的最大數值!", 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) { //檔案上傳成功後返回的資料, 此處我只儲存返迴文件的id var result = outData.response.id; // 對應的input 賦值 $('#htestlogo').val(result).change(); }); }

4. 後台java儲存檔案部分代碼

@RequestMapping(value="/uploadFile",method=RequestMethod.POST) @ResponseBody public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //轉型為MultipartHttpServletRequest MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request; //擷取檔案到map容器中 Map<String,MultipartFile> fileMap = multipartRequest.getFileMap(); //擷取頁面傳遞過來的路徑參數 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; } 

說明:該段代碼為擷取上傳檔案的部分資訊, 如檔案名稱,上傳的路徑 等,將檔案資訊儲存到表中,對應對象為 FileModel 。

5.上傳完成後重新重新整理該組件即可。

最終展示效果 :

說明:此處指標對txt檔案類型判斷, 其餘的doc,ppt裡面有對應的展示表徵圖,只須在判斷是添加對應樣式即可

附:根據路徑過去/下載檔案代碼:

/** * 檔案下載 * * @param savePath * 儲存目錄 * @param name * 檔案原名 * @param file * 儲存時的名稱 包含尾碼 * @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"); // 根據不同瀏覽器 設定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/*"); // 設定返回的檔案類型 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); //判斷檔案夾是否存在,如果不存在則建立檔案夾 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作為儲存時的檔案名稱 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 多圖片上傳編輯,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對幫客之家網站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.