Bootstrap-fileinput 多图片上传编辑

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

前言 :关于Bootstrap-fileinput 如何配置不做说明,自行去官网查看。网址 : http://plugins.krajee.com/file-input

逻辑说明:先从后台获取数据展示,然后进行编辑。

废话不多说, 直接上代码.

1. 页面部分代码:

  1. <div class="form-group">  
  2.      <label for="inputEmail3" class="col-xs-3 control-label">项目LOGO</label>  
  3.      <div class="col-xs-7">  
  4.          <input id="testlogo" type="file" name="icoFile"   class="file-loading" />  
  5.          <input type="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.      
  16.   });  
说明:此处我返回是一个 对象数组: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]= "<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>"  
  12.         }else{  
  13.             // 图片类型  
  14.             preList[i]= "<img src=\"/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: '<i class="fa fa-file"></i>',  
  46.          allowedPreviewTypes: ['image'],   
  47.          previewFileIconSettings: {  
  48.              'docx': '<i class="fa fa-file-word-o text-primary"></i>',  
  49.              'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',  
  50.              'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',  
  51.              'pdf': '<i class="fa fa-file-pdf-o text-danger"></i>',  
  52.              'zip': '<i class="fa fa-file-archive-o text-muted"></i>',  
  53.              'sql': '<i class="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.               
  20.             //返回文件保存ID  
  21.             //response.getWriter().write(map);  
  22.             return map;  
  23.         }  
  24.         return null;  
  25.     }  
说明:该段代码为获取上传文件的部分信息, 如文件名,上传的路径 等,将文件信息保存到表中,对应对象为 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.   
  28.             if (userAgent.indexOf("msie") != -1) {  
  29.                 // ie浏览器  
  30.                 // System.out.println("ie浏览器");  
  31.                 response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));  
  32.   
  33.             } else {  
  34.                 response.addHeader("Content-Disposition",  
  35.                         "attachment;filename=" + new String(name.getBytes("utf-8"), "ISO8859-1"));  
  36.             }  
  37.   
  38.             response.addHeader("Content-Length", "" + file.length());              
  39.             // 以流的形式下载文件  
  40.             InputStream fis = new BufferedInputStream(new FileInputStream(path));  
  41.             byte[] buffer = new byte[fis.available()];  
  42.             fis.read(buffer);  
  43.             fis.close();  
  44.             //response.setContentType("image/*"); // 设置返回的文件类型  
  45.             OutputStream toClient = response.getOutputStream();  
  46.             OutputStream bos = new BufferedOutputStream(toClient);  
  47.             //BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(bos));  
  48.             bos.write(buffer);  
  49.             //bw.close();  
  50.             bos.close();  
  51.             toClient.close();  
  52.             return null;  
  53.         } catch (Exception e) {  
  54.             e.printStackTrace();  
  55.             //response.reset();  
  56.             return "exception";// 返回异常页面  
  57.         } finally {  
  58.            /* if (toClient != null) {  
  59.                 try {  
  60.                     toClient.close();  
  61.                 } catch (IOException e) {  
  62.                     e.printStackTrace();  
  63.                 }  
  64.             }*/  
  65.   
  66.         }  
  67.     }  

附:

  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.               
  28.         }catch (Exception e) {  
  29.             log.error(e);  
  30.             return null;  
  31.         }  
  32.     }  

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

优化修改:

上面的文件下载方法有一个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.                       
  25.                     HttpHeaders headers = new HttpHeaders();      
  26.                     fileName=new String(fileName.getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题    
  27.                     headers.setContentDispositionFormData("attachment", fileName);     
  28.                     headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);     
  29.                     return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),      
  30.                                                       headers, HttpStatus.CREATED);    
  31.                 }  
  32.         }catch (Exception e) {  
  33.             e.printStackTrace();  
  34.             throw new BusinessException("1014", "附件下载错误:"+e.getMessage());  
  35.         }  
  36.         return null;  
  37.      }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值