layui实现图片上传 和 预览功能

效果如下:

HTML 的代码:

<div class="box" style="width: 180px;float: left;">
	<div class="layui-upload">
		<div class="layui-row layui-col-space1">
	    <div class="layui-col-md6">
	    <button type="button" class="layui-btn layui-btn-sm" id="upLoadImge" style="width: 88px;">图片上传</button>
	    </div>
		    <div class="layui-col-md6">
		     <button type="button" class="layui-btn layui-btn-sm" id="deleteImge" style="width: 88px;">删除图片</button>
	    </div>
	  </div>
		<div class="layui-upload-list" id="imgeList" style="overflow-y:auto;">
         //查询到已上传图片返回页面
		<#list siteCFileList as entity>
		<a> <img  width="160" height="80" src="${entity.fileUrl}" data-fileid="${entity.id}" class="layui-upload-img" style="margin-bottom: 2px;"></a>
		</#list>
		</div>
		</blockquote>
</div>
//每次插入 图片id 提交保存时更新 图片关联的文章
<input type="hidden" id="fileIds"  value="">

JS的代码:

layui.use('upload', function() {
	var upload = layui.upload;
	// 多图片上传
	upload.render({
		elem: '#upLoadImge',
		url: '/gcsoft/file/saveFile.action?relId=' +$("#itemId").val(),
		multiple: true,
		done: function(res) {
			$('#imgeList').append(
					'<a> <img  width="160" height="80" src="' +
					res.src +
					'" data-fileid="' +
					res.id +
					'" class="layui-upload-img" style="margin-bottom: 2px;"></a>')
			
			pushFileId();
		}
	});
});
//放入 input中 用在文章新增的时候保存 关联的文章ID
function pushFileId (){
	$('#imgeList img').each(function() {
	fileIds.push($(this).attr('data-fileid'));
	$("#fileIds").val(fileIds.toString());
	});	
}

// 这里是吧选择图片 选着的图片放入 form 表单中 封面图片imgUrl里
//因为是上传的文件是动态添加 多以要用 $(document).on('click', '#imgeList a', function(){})
// 可点击动态添加的元素
$(document).on('click', '#imgeList a', function() {
	$('#imgeList a').each(function() {
		$(this).removeClass('imgChose')
	});
	$(this).addClass('imgChose')
	$("#imgUrl").val($(this).find('img').attr('src'))
});
//由于新增文章的时候,还没有生成ID主键 ,上传图片时候,关联Id,为null,这里主要把$("#fileIds").val()里图片 和 关联的文章ID更新
 $("#submit").click(function(){
     $("#content").val(layedit.getContent(index));
     //提交
      if($("#menuId").val()==''||$("#menuId").val()==-1){
		   layer.msg('请选择所属栏目');
	  }else{
		   $.ajax({
                type: "POST",
                dataType: "json",
               //传入需要关联的图片ID
                url: "/gcsoft/news/addOrUpdateNews.action?fileIds="+$("#fileIds").val(),
                data: $('#newsFrom').serialize(),
                success: function (result) {    
                    layer.msg('保存成功!');
                    var index = parent.layer.getFrameIndex(window.name);
					parent.layer.close(index);
                },
                error : function() {
                    alert("异常!");
                }
            });
	  };
 });

java 端代码:

1.保存文件到指定目录,并保存保存地址

	@RequestMapping(value = "/saveFile")
	@ResponseBody
	public HashMap<String, Object> saveUser(HttpServletRequest request, HttpServletResponse response) {
		Integer relId = request.getParameter("relId")!=null&&!"".equals(request.getParameter("relId")) ? new Integer(request.getParameter("relId")) : null;
		HashMap<String, Object> map =  new HashMap<String, Object>();
		// 文件保存目录URL
		String saveUrl = "/upload/";
		// 文件保存目录路径
		String savePath = request.getServletContext().getRealPath("/");
		savePath = savePath.substring(0, savePath.length() - 1);
		savePath = savePath.substring(0, savePath.lastIndexOf("\\"));
		savePath += saveUrl;
		// 定义允许上传的文件扩展名
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", "gif,jpg,jpeg,png,bmp");
		// 最大文件大小
		long maxSize = 2000000000;
		String dirName = "image";
		// 创建文件夹
		savePath += dirName + "/";
		saveUrl += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ymd = sdf.format(new Date());
		savePath += ymd + "/";
		saveUrl += ymd + "/";
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}

		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		List items = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e1) {
			e1.printStackTrace();
		}
		Iterator itr = items.iterator();
		String newFileName = "";
		while (itr.hasNext()) {
			FileItem item = (FileItem) itr.next();
			String fileName = item.getName();
			long fileSize = item.getSize();

			if (!item.isFormField()) {
				// 检查文件大小
				if (item.getSize() > maxSize) {
					map.put("msg", "上传文件大小超过限制。");
					return map;
				}
				// 检查扩展名
				String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                 try {
                	 Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt);
				} catch (Exception e) {
					System.out.println(e);
				}
				if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
					map.put("msg", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。");
					return map;
				}

				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000)+"." + fileExt;
				try {
					File uploadedFile = new File(savePath, newFileName);
					item.write(uploadedFile);
				} catch (Exception e) {
					System.out.println(e);
					map.put("msg", "上传文件失败。");
					return map;
				}
			}
		}

               //保存 上传的文件 
		SiteCFile entity = new SiteCFile();
		entity.setCreateTime(new Date());
		entity.setRelId(relId);
		entity.setFileUrl(saveUrl+newFileName);
		siteCFileService.save(entity);
		
		map.put("src",saveUrl+newFileName);
		map.put("id",entity.getId());
		return map;
	}

 2.在新增时,更新图片关联 文章的ID

//先保存文章生成ID
siteCMenuInfoService.insert(news);
//在更新 图片对应的文章ID
String fileIds = request.getParameter("fileIds");
String[] fileIdArr = fileIds!=null&&!"".equals(fileIds)? fileIds.split(",") : null;
for (String id : fileIdArr) {
	SiteCFile entity = siteCFileService.getFileById(new Integer(id));
	entity.setRelId(news.getItemId());
	siteCFileService.update(entity);
}

猜你喜欢

转载自blog.csdn.net/q6658368/article/details/81286658