1. 程式人生 > >Bootstrap-fileinput 多圖片上傳編輯

Bootstrap-fileinput 多圖片上傳編輯

轉自:http://blog.csdn.net/wuwenjinwuwenjin/article/details/49507595

前言 :關於Bootstrap-fileinput 如何配置不做說明,自行去官網檢視。網址 : http://plugins.krajee.com/file-input

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

廢話不多說, 直接上程式碼.

1. 頁面部分程式碼:

  1. <divclass="form-group">
  2.      <labelfor="inputEmail3"class="col-xs-3 control-label">專案LOGO</label
    >
  3.      <divclass="col-xs-7">
  4.          <inputid="testlogo"type="file"name="icoFile"class="file-loading"/>
  5.          <inputtype="text"name="htestlogo"id="htestlogo"onchange="addFile(this)">
  6.      </div>
  7. </div>

說明: 其中onchange()為我業務需要, 上傳完成後自動執行一個新增事件。 此方法可以去掉。

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

  1. // 初始化獲取原有檔案  
  2.   $(function(){  
  3.     $.ajax({  
  4.        type : "post",  
  5.        url : "/eim/project/testFileUpload.do",  
  6.        dataType : "json",  
  7.        success : function(data) {  
  8.         layer.msg('操作成功!');  
  9.         showPhotos(data);  
  10.        },  
  11.        error: function(XMLHttpRequest, textStatus, errorThrown) {  
  12.               layer.msg('操作失敗!');  
  13.                    }  
  14.    });  
  15.   });  
說明:此處我返回是一個 物件陣列:List<MemberUser>,可以理解為獲取一個班中所有的學生,展示頭像

3.初始化bootstrap-fileinput 元件:

  1. function showPhotos(djson){  
  2.      //後臺返回json字串轉換為json物件      
  3.      var reData = eval(djson);  
  4.      // 預覽圖片json資料組  
  5.      var preList = new Array();  
  6.      for ( var i = 0; i <reData.length; i++) {  
  7.         var array_element = reData[i];  
  8.         // 此處指標對.txt判斷,其餘自行新增  
  9.         if(array_element.fileIdFile.name.indexOf("txt")>0){  
  10.             // 非圖片型別的展示  
  11.             preList[i]= "<divclass='file-preview-other-frame'><divclass='file-preview-other'><spanclass='file-icon-4x'><iclass='fa fa-file-text-o text-info'></i></span></div></div>"  
  12.         }else{  
  13.             // 圖片型別  
  14.             preList[i]= "<imgsrc=\"/eim/upload/getIMG.do?savePath="+array_element.fileIdFile.filePath+"&name="+array_element.fileIdFile.name+"\" class=\"file-preview-image\">";  
  15.         }  
  16.      }  
  17.      var previewJson = preList;  
  18.      // 與上面 預覽圖片json資料組 對應的config資料  
  19.      var preConfigList = new Array();  
  20.      for ( var i = 0; i <reData.length; i++) {  
  21.         var array_element = reData[i];  
  22.         var tjson = {caption: array_element.fileIdFile.fileName, // 展示的檔名  
  23.                     width: '120px',   
  24.                     url: '/eim/project/deleteFile.do', // 刪除url  
  25.                     key: array_element.id, // 刪除是Ajax向後臺傳遞的引數  
  26.                     extra: {id: 100}  
  27.                     };  
  28.         preConfigList[i] = tjson;  
  29.      }  
  30.      // 具體引數自行查詢  
  31.      $('#testlogo').fileinput({  
  32.          uploadUrl: '/eim/upload/uploadFile.do',  
  33.          uploadAsync:true,  
  34.          showCaption: true,  
  35.          showUpload: true,//是否顯示上傳按鈕  
  36.          showRemove: false,//是否顯示刪除按鈕  
  37.          showCaption: true,//是否顯示輸入框  
  38.          showPreview:true,   
  39.          showCancel:true,  
  40.          dropZoneEnabled: false,  
  41.          maxFileCount: 10,  
  42.          initialPreviewShowDelete:true,  
  43.          msgFilesTooMany: "選擇上傳的檔案數量 超過允許的最大數值!",  
  44.          initialPreview: previewJson,  
  45.          previewFileIcon: '<iclass="fa fa-file"></i>',  
  46.          allowedPreviewTypes: ['image'],   
  47.          previewFileIconSettings: {  
  48.              'docx': '<iclass="fa fa-file-word-o text-primary"></i>',  
  49.              'xlsx': '<iclass="fa fa-file-excel-o text-success"></i>',  
  50.              'pptx': '<iclass="fa fa-file-powerpoint-o text-danger"></i>',  
  51.              'pdf': '<iclass="fa fa-file-pdf-o text-danger"></i>',  
  52.              'zip': '<iclass="fa fa-file-archive-o text-muted"></i>',  
  53.              'sql': '<iclass="fa fa-file-word-o text-primary"></i>',  
  54.          },  
  55.          initialPreviewConfig: preConfigList  
  56.      }).off('filepreupload').on('filepreupload', function() {  
  57. //                                  alert(data.url);  
  58.      }).on("fileuploaded", function(event, outData) {  
  59.             //檔案上傳成功後返回的資料, 此處我只儲存返回檔案的id  
  60.             var result = outData.response.id;  
  61.             // 對應的input 賦值  
  62.             $('#htestlogo').val(result).change();  
  63.      });  
  64. }  

4. 後臺java儲存檔案部分程式碼
  1. @RequestMapping(value="/uploadFile",method=RequestMethod.POST)  
  2.     @ResponseBody  
  3.     public Object uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  4.         //轉型為MultipartHttpServletRequest  
  5.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;  
  6.         //獲取檔案到map容器中  
  7.         Map<String,MultipartFile>fileMap = multipartRequest.getFileMap();  
  8.         //獲取頁面傳遞過來的路徑引數  
  9.         folderPath = request.getParameter("folder");  
  10.         String rootPath = BaseConfig.uploadPath;  
  11.         String filePath = rootPath + folderPath+"/";  
  12.         //檔案上傳並返回map容器,map儲存了檔案資訊  
  13.         FileModel fileModel = UploadifyUtils.uploadFiles(filePath,fileMap);  
  14.         boolean flag = service.add(fileModel);  
  15.         if(flag){  
  16.             String result = fileModel.getId()+";"+fileModel.getFilePath()+";"+fileModel.getName()+";"+fileModel.getFilePath();  
  17.             Map map = new HashMap<>();  
  18.             map.put("id", fileModel.getId());  
  19.             //返回檔案儲存ID  
  20.             //response.getWriter().write(map);  
  21.             return map;  
  22.         }  
  23.         return null;  
  24.     }  
說明:該段程式碼為獲取上傳檔案的部分資訊, 如檔名,上傳的路徑 等,將檔案資訊儲存到表中,對應物件為 FileModel 。

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

最終展示效果 :

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

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

  1. /**  
  2.      * 檔案下載  
  3.      *   
  4.      * @param savePath  
  5.      *            儲存目錄  
  6.      * @param name  
  7.      *            檔案原名  
  8.      * @param file  
  9.      *            儲存時的名稱 包含字尾  
  10.      * @param request  
  11.      * @param response  
  12.      * @return  
  13.      */  
  14.     public static String down(String savePath, String name, String fileName, HttpServletRequest request,  
  15.             HttpServletResponse response) {  
  16.         try {  
  17.             String path = savePath + "/" + name;  
  18.             File file = new File(path);  
  19.             if (!file.exists()) {  
  20.                 // 不存在  
  21.                 request.setAttribute("name", fileName);  
  22.                 return "download_error";// 返回下載檔案不存在  
  23.             }  
  24.             response.setContentType("application/octet-stream");  
  25.             // 根據不同瀏覽器 設定response的Header  
  26.             String userAgent = request.getHeader("User-Agent").toLowerCase();  
  27.             if (userAgent.indexOf("msie") != -1) {  
  28.                 // ie瀏覽器  
  29.                 // System.out.println("ie瀏覽器");  
  30.                 response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));  
  31.             } else {  
  32.                 response.addHeader("Content-Disposition",  
  33.                         "attachment;filename=" + new String(name.getBytes("utf-8"), "ISO8859-1"));  
  34.             }  
  35.             response.addHeader("Content-Length", "" + file.length());              
  36.             // 以流的形式下載檔案  
  37.             InputStream fis = new BufferedInputStream(new FileInputStream(path));  
  38.             byte[] buffer = new byte[fis.available()];  
  39.             fis.read(buffer);  
  40.             fis.close();  
  41.             //response.setContentType("image/*"); // 設定返回的檔案型別  
  42.             OutputStream toClient = response.getOutputStream();  
  43.             OutputStream bos = new BufferedOutputStream(toClient);  
  44.             //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(bos));  
  45.             bos.write(buffer);  
  46.             //bw.close();  
  47.             bos.close();  
  48.             toClient.close();  
  49.             return null;  
  50.         } catch (Exception e) {  
  51.             e.printStackTrace();  
  52.             //response.reset();  
  53.             return "exception";// 返回異常頁面  
  54.         } finally {  
  55.            /* if (toClient != null) {  
  56.                 try {  
  57.                     toClient.close();  
  58.                 } catch (IOException e) {  
  59.                     e.printStackTrace();  
  60.                 }  
  61.             }*/  
  62.         }  
  63.     }  

附:

  1. UploadifyUtils.uploadFiles 部分程式碼  
  1. public static FileModel uploadFiles(String savePath,Map<String,MultipartFile> fiLeMap){  
  2.         //上傳檔案  
  3.         //附件模型物件  
  4.         FileModel fm=new FileModel();  
  5.         try {  
  6.             File file = new File(savePath);  
  7.             //判斷資料夾是否存在,如果不存在則建立資料夾  
  8.             makeDir(file);  
  9.             if(fiLeMap!=null){  
  10.                 for(Map.Entry<String, MultipartFile> entity:fiLeMap.entrySet()){  
  11.                     MultipartFile f = entity.getValue();  
  12.                     if(f!=null&&!f.isEmpty()){  
  13.                         String uuid=UploadifyUtils.getUUID();//uuid作為儲存時的檔名  
  14.                         String ext=UploadifyUtils.getFileExt(f.getOriginalFilename());//獲取檔案字尾  
  15.                         //儲存檔案  
  16.                         File newFile = new File(savePath+"/"+uuid+"."+ext);   
  17.                         f.transferTo(newFile);  
  18.                         fm.setFileName(f.getOriginalFilename());  
  19.                         fm.setName(uuid+"."+ext);  
  20.                         fm.setFilePath(savePath);//儲存路徑  
  21.                         fm.setExt(ext);  
  22.                         fm.setSize(f.getSize());  
  23.                     }  
  24.                 }  
  25.             }  
  26.             return fm;  
  27.         }catch (Exception e) {  
  28.             log.error(e);  
  29.             return null;  
  30.         }  
  31.     }  

****************************************************************************************************************************************************************************

優化修改:

上面的檔案下載方法有一個bug。當上傳的檔名中存在特殊在字元( ,[] )時會導致無法下載。 可以改為使用spring下載代替流的方式。下面是程式碼:

  1. /**  
  2.      * @version 1.0  
  3.      * @Title: downLoad  
  4.      * @Description: spring下載附件  
  5.      * @param fileId 附件id   
  6.      * @param HttpServletRequest  
  7.      * @param HttpServletResponse  
  8.      * @author qcym  
  9.      * @date 2016年9月6日15:55:49  
  10.      * @throws  
  11.      */  
  12.      @RequestMapping(value="/downLoad")  
  13.      public ResponseEntity<byte[]> downLoad(String fileId,HttpServletRequest request,HttpServletResponse response){  
  14.          try {  
  15.                 // 附件id不為空  
  16.                 if(StringUtils.isNotEmpty(fileId)){  
  17.                 // 獲取附件資訊  
  18.                 MailFile mailFile = fileDao.selectByPrimaryKey(fileId);  
  19.                 // 獲取附件真是名稱  
  20.                 String fileName = mailFile.getFileRealname();  
  21.                 // 獲取伺服器上的檔案  
  22.                 String filePath = mailFile.getFileUrl()+mailFile.getFileName();  
  23.                     File file = new File(filePath);  
  24.                     HttpHeaders headers = new HttpHeaders();      
  25.                     fileName=new String(fileName.getBytes("UTF-8"),"iso-8859-1");//為了解決中文名稱亂碼問題    
  26.                     headers.setContentDispositionFormData("attachment", fileName);     
  27.                     headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);     
  28.                     return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),      
  29.                                                       headers, HttpStatus.CREATED);    
  30.                 }  
  31.         }catch (Exception e) {  
  32.             e.printStackTrace();  
  33.             throw new BusinessException("1014", "附件下載錯誤:"+e.getMessage());  
  34.         }  
  35.         return null;  
  36.      }