您现在的位置是:网站首页>博客详情博客详情

关于layui图片上传

凡繁烦2019-05-27 11:10前端技术2633人已围观

简介layui图片异步上传,并实现上传图片回显,采用后台用的是SpringMVC,要注意的细节有很多。

layui图片异步上传前端jsp配置

<div class="am-g am-margin-top-sm">
				  <ul class="am-u-sm-2 am-u-sm-centered">
				  	<li><img class="am-circle" src="${user.head}" alt="" width="140" height="140" id="headpic"/></li>
				  	<li class="am-u-sm-centered am-margin-top-sm" ><a class="am-btn am-btn-primary" id="changePic">修改头像</a></li>
				  </ul>
			</div>

js配置

layui.use(['laydate','util','upload'], function(){
  var laydate = layui.laydate
  ,upload = layui.upload
  ,util = layui.util;
  
  //普通图片上传
  var uploadInst = upload.render({
    elem: '#changePic'
    ,url: '<%=path%>/system/file/headUl'
    ,before: function(obj){
      //预读本地文件示例,不支持ie8
      obj.preview(function(index, file, result){
        $('#headpic').attr('src', result); //图片链接(base64)
        $('#topHead').attr('src',result);
      });
    }
    ,done: function(res){
      //如果上传失败
      if(res.code > 0){
        return layer.msg('上传失败');
      }
      //上传成功
    }
    ,error: function(){
      //演示失败状态,并实现重传
      var demoText = $('#demoText');
      demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
      demoText.find('.demo-reload').on('click', function(){
        uploadInst.upload();
      });
    }
  });

java后台代码

/**
	 * 头像图片上传
	 * @return
	 */
	@RequestMapping(value="headUl")
	public @ResponseBody Map<String ,Object> headPic(){
		Map<String ,Object> map = new HashMap<String, Object>();
		//得到图片处理结果集
		Map<String,Object> resMap = FileUtil.fileUpLoad("headpic", request,false);
		if(resMap!=null){
			User user = getUser(request, response);
			//得到用户之前的头像文件名
			String head = user.getHead();
			//得到新头像
			String newHead = String.valueOf(resMap.get("fileName"));
			newHead = "/csvims/file/image/headpic/"+newHead;
			if(userService.changeHeadPic(new User(user.getUid(), newHead))&&FileUtil.FileRemove(head, request)){
				map.put("msg","success");
			}
			user.setHead(newHead);
			//更新session里的头像
			session.setAttribute("user", user);
		}else{
			map.put("msg","图片上传失败");
		}
		return map;
	}

文件上传工具类

/**
	 * 文件上传
	 * @param path
	 * @param request
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String,Object> fileUpLoad(String path, HttpServletRequest request,boolean flag) {
		Map<String,Object> map = new HashMap<String, Object>();
		// 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
					String url = request.getSession().getServletContext().getRealPath("/") + "/file/image/" + path+"/";
					if (!new File(url).exists()) {
						new File(url).mkdirs();
					}
					String fname = file.getOriginalFilename();
					String[] fn = fname.split("\\.");
					String fileName = System.currentTimeMillis()+"."+fn[fn.length-1];
					// 上传
					try {
						file.transferTo(new File(url+fileName));
						//上传头像
						if(flag){
							ImgUtils.thumbnailImage(url+fileName, 160, 160, "", true);
						}
						map.put("res", true);
						map.put("fileName", fileName);
					} catch (Exception e) {
						log.addError("图片:"+file.getOriginalFilename()+"上传异常,异常原因:", e);
					}finally{
						
					}
				}

			}
		}
		return map;
	}

 

很赞哦! (0)

文章评论(共0条)

{{item.createTime}} {{item.commentArea}} |({{item.commentIp}})
{{it.createTime}}{{it.commentArea}} | ({{it.commentIp}})
上一页 1 ... {{num}} ... 下一页 {{totalPage}} 跳转到: GO

站点信息

  • 建站时间:2020-03-28
  • 开发语言:JAVA
  • 文章统计:13篇
  • 文章评论:4条
  • 统计数据百度统计
  • 微博:扫描二维码,关注

打赏本站

  • 如果你觉得本站很棒,可以通过扫码支付打赏哦!
  • 微信扫码:你说多少就多少~
  • 支付宝:非常感谢您的慷慨支持~