mtjmtj7的小站
mtjmtj7的小站
© mtjmtj7
All Rights Reserved.

Springboot+LayUI上传图片

1,要注意配置文件允许上传大小

2,LayUI中:

//上传头像
		layui.use('upload', function(){
		  var upload = layui.upload;
		  var $=layui.jquery
		  //执行实例
		  var uploadInst = upload.render({
		    elem: '#upload' //绑定元素
		    ,url: '/admin/uploadImg/' //上传接口
		    ,done: function(data){
		      //上传完毕回调
		      layer.msg("上传成功")
		      $("#head").attr("src","/	img/"+data.uri)
		      
		    }
		    ,error: function(res){
		      //请求异常回调
		      layer.msg("上传失败")
		    }
		  });
		});

3,后台:

  1. controller
    //上传头像
    	@RequestMapping("uploadImg")
    	@ResponseBody
    	public String uploadImg(MultipartFile file,HttpServletRequest request,HttpSession session) {
    		User userNow = (User)session.getAttribute("userNow");
    		Map<String,String> map = new HashMap<String,String>();
    		if(!file.isEmpty()) {
    			userService.savaImg(request, userNow,file);
    			//更新数据库
    			userService.updateImg(userNow);
    			map.put("msg","yes");
    			map.put("code","1");
    			map.put("uri",userNow.getUserimg());
    		}
    		else {
    			map.put("msg","no");
    			map.put("code","0");
    		}
    		return JSONObject.toJSONString(map);
    	}

     

  2. service
    /**
    	 * 保存图片
    	 */
    	public void savaImg(HttpServletRequest request,User user,MultipartFile file) {
    		String path = request.getServletContext().getRealPath("img/");
    		File filepath  = new File(path);
    		if(!filepath.exists()) {
    			filepath.mkdirs();
    		}
    		//上传文件原始文件名
    		String filename = file.getOriginalFilename();
    		String[] arr = filename.split("\\.");
    		String ext = arr[arr.length-1];
    		String newFileName = new Date().getTime()+"."+ext;//修改上传图片名字
    		//创建上传后文件的路径和文件名
    		File name = new File(filepath,newFileName);
    		File oldFile = new File(filepath,user.getUserimg());
    		try {
    			if(oldFile.exists()) {
    				oldFile.delete();
    			}
    			file.transferTo(name);
    		} catch (IllegalStateException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		user.setUserimg(newFileName);
    	}
    	/**
    	 * 更新图片
    	 * @return 
    	 */
    	public User updateImg(User user) {
    		return userDao.save(user);
    	}

     

  3. dao层使用spring-data-jpa   save()方法更新数据库
打赏
2019-01-15
52 阅读
暂无评论

发表评论