目前正在进行的项目中,后台需要实现一次性上传多张图片的功能,现记录实现的过程如下。
1.设置功能方法的点击事件
var imga = '<a href="#" onclick="imgrow(\'' + id + '\')">'+imgTitle; //携带该记录的主键id过去
2.点击方法的具体实现
html DOM对象
<div id="myImg" style="overflow-x:hidden" sec:authorize="hasRole('GOODS_VIEW')"></div>
function imgrow(id) { var imgTitle = '图片'; if(!top.checkHiddenSet("plateNumFlag")){ imgTitle = '车辆图片管理'; } var detailLog= $('#myImg').dialog( { title: imgTitle,//这里动态设置标题显示 width: 945, height: '90%', modal: true, closable:true, href: "goods/indexImg?id="+id,//跳转到图片展示的dialog对话框中 onLoad: function () { img(id);//图片的回显方法 }, buttons : [ { text : "关闭", handler : function() { $('#t_goods').datagrid('reload'); $('#t_goods').datagrid('unselectAll'); detailLog.dialog('close'); } } ], onClose:function(){//关闭右上方红叉的方法 fileNums = [];//清空图片id数组 $('#t_goods').datagrid('reload'); $('#t_goods').datagrid('unselectAll'); } }); // $("#id").val(id); };
3.回显方法img()的实现
function img(id){ //id是标的id $.ajax({ type: "get", async: false, dataType : 'json', url: parent.baseUrl+"goods/findGoodsimg/" + id, //获取关于该记录的所有的图片的信息 success: function (result) { var json = eval(result);//循环遍历获取到的图片信息的情况 showGoodsImgs(id,json);//显示记录关联的图片信息情况 createImgContainer(id,json);//创建一次向上传多张图片的容器 } }); }
控制器中获取记录的图片信息的具体方法
/** * 查询单个标的的图片 */ @RequestMapping(value = "/findGoodsimg/{id}", method = RequestMethod.GET) @ResponseBody public List<GoodsImageDTO> findGoodsImg(@PathVariable("id") Long id, GoodsCreateOrUpdateModel goods, BindingResult result) { logger.debug("进入单个标的的图片查询。。。。。。。"); Long goodsId = id; if (logger.isDebugEnabled()) { logger.debug("merchantCreate, id{},merchantName: {}.", goods.getId(), goods.getName()); } Specification<GoodsImage> spec = (root, query, cb) -> { List<Predicate> predicates = new ArrayList<Predicate>(); if (goodsId != null) { Predicate predicate = cb.equal(root.get(GoodsImage_.goodsId), goodsId); predicates.add(predicate); } if (!predicates.isEmpty()) { return cb.and(predicates.toArray(new Predicate[0])); } else { return null; } }; List<GoodsImage> typeList = goodsImageRepository.findAll(spec); List<GoodsImageDTO> dtoList = (new GoodsImageDTOAssembler()).toDTOList(typeList); if (dtoList != null && dtoList.size() > 0) { AttachmentFile attachmentFile = null; for (GoodsImageDTO goodsImage : dtoList) { attachmentFile = attachmentFileService.findById(goodsImage.getFileId()); if (attachmentFile != null) { goodsImage.setFilePath(attachmentFile.path()); goodsImage.setOriginalName(attachmentFile.originalName()); goodsImage.setFileCount(dtoList.size()); } } } return dtoList; }
显示记录关联的图片信息的方法
<div>
<div id="detailImg"></div>
<div id="img-container"></div>
</div>
/** * 显示关联图片 */ function showGoodsImgs(id,json){ document.getElementById('detailImg').innerHTML = renderGoodsImgs(id,json); imgCount = json.length; }
回显图片的格式化显示的方法
function renderGoodsImgs(id,json){ var previewImgUrl = parent.baseUrl + "file/previewImg/";//定义图片的路径的方法 var detail=""; detail+='<table>'; detail+='<tr style="height:1px;">'; detail+='<td><input style="height:1px;" type="hidden" name="id" value="'+id+'" /></td>'; detail+='</tr>'; if(!top.checkHiddenSet("plateNumFlag")){ //客制化显示信息 detail+='<tr style="width:100%;" align="center"><br/><br/>'; detail+='<b><font color="#FF0000" size="4px">'; detail+=' 提示:请至少上传4张照片,分别为车辆左前45°、车辆右后45°、前排内饰图、后排内饰图。'; detail+='</font></b>'; detail+='</tr>'; } detail+='<tr>'; if(json.length <= 5){ for (var int = 0; int < 5; int++) { detail+='<td style="height: 1px;visibility:hidden">'; if(int == 0){ detail+=' '; } detail+='<img src="/admin/file/previewImg/1638/160x1"/>'; detail+='</td>'; } detail+='</tr>'; detail+='<tr>'; for (var int = 0; int < json.length; int++) { if(int == 0){ detail+=' '; } detail+='<img src="'+previewImgUrl+json[int].fileId+'/160x100"/><br/>'; if(top.checkRole(['GOODS_EDIT'])){ if(int == 0){ detail+=' '; } detail+=' '; detail+='<input onclick="showDel('+json[int].id+','+json[int].goodsId+','+json[int].fileId+')" id="ehdel_del_btn" type="button" value="删 除 " style="margin-left:22px;" />'; } detail+='</td>'; } } if(json.length > 5){ for (var int = 0; int < 5; int++) { detail+='<td>'; if(int == 0){ detail+=' '; } detail+='<img src="'+previewImgUrl+json[int].fileId+'/160x100"/><br/>'; if(top.checkRole(['GOODS_EDIT'])){ if(int == 0){ detail+=' '; } detail+=' '; detail+='<input onclick="showDel('+json[int].id+','+json[int].goodsId+','+json[int].fileId+')" id="ehdel_del_btn" type="button" value="删 除 " style="margin-left:22px;" />'; } detail+='</td>'; } detail+='</tr>'; detail+='<tr>'; for (var int = 5; int < json.length; int++) { detail+='<td>'; if(int == 5){ detail+=' '; } detail+='<img src="'+previewImgUrl+json[int].fileId+'/160x100"/><br/>';
//根据权限动态显示是否能够删除的一些信息情况 if(top.checkRole(['GOODS_EDIT'])){ if(int == 5){ detail+=' '; } detail+=' '; detail+='<input onclick="showDel('+json[int].id+','+json[int].goodsId+','+json[int].fileId+')" id="ehdel_del_btn" type="button" value="删 除 " style="margin-left:22px;" />'; } detail+='</td>'; } } detail+='</tr>'; detail+='</table>'; return detail; }
4.图片上传容器的方法的实现
<div id="img-container"></div>
/** * 创建图片容器,用来显示要上传的图片 */ function createImgContainer(id,json){ document.getElementById('img-container').innerHTML = imgContainer(id,json); //multiple的input组件加载后才能初始化ImgLoader var imgUploadUrl = parent.baseUrl+'file/uploadImg?filePath=aucimg_'+$("#type").val(); initImgLoader("fileupload", imgUploadUrl); }
初始化多个上传图片容器的方法
function imgContainer(id,json){ var detail = ''; if(json.length > 9){
//异常信息提示 }else if(top.checkRole(['GOODS_EDIT'])){ detail += '<table class="formTable">'; detail += '<tr><td><div class="uploads_container">'; detail += '<div class="uploads_container_sublocation">'; detail += '<input id="fileupload" style="display:none" type="file" name="file" multiple="multiple"/>'; detail += '</div>'; detail += '<span id="add_text">添加图片</span>'; detail += '</div></td></tr>'; detail += '<tr><td><div style="display:block;margin:0 auto;width:150px">'; detail += '<input onclick="bundGoodsClick();" id="addimg" type="button" value="添 加 " style="float:left;margin-top:20px;display:inline-block"/>'; detail += '<input onclick="showUploding('+id+')" id="uploding" type="button" value="上 传 " style="float:right;margin-top:20px;display:inline-block"/>'; detail += '</div></td></tr>'; detail += '</table>'; } return detail; }
initImgLoader 方法的具体实现
/** * 初始化ImgLoader,响应文件添加并自动上传 */ function initImgLoader(id, url){ $('#'+id).fileupload({ url: url, dataType: 'json', autoUpload: true, acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, maxFileSize: 999000, disableImageResize: /Android(?!.*Chrome)|Opera/ .test(window.navigator.userAgent) }).on('fileuploadadd', function (e, data) { //添加文件事件 }).on('fileuploadprocessalways', function (e, data) { }).on('fileuploadprogressall', function (e, data) { //文件上传事件 }).on('fileuploaddone', function (e, data) { var fileNum=data._response.result; addImgToContainer(fileNum); fileNums.push(fileNum); }).on('fileuploadfail', function (e, data) { alert("文件上传失败"); }); }
上传事件方法
/** * 点击上传 */ function showUploding(id){ if(fileNums.length + imgCount > 10){ alert("图片总数超出上限(10)!!!"); } else if(fileNums == null && fileNums.length == 0){ alert("请先添加图片!!!"); } else { $.each(fileNums,function(key, val){ goodsImage(id,val); }); } }