layui upload photo interface

 

 1. layui (homonym: UI-like) is a front-end UI framework written with its own module specifications, following the writing and organization of native HTML/CSS/JS, with a very low threshold and ready-to-use. Its appearance is minimal, yet full of inner, light in size and rich in components. Every detail from the core code to the API has been carefully crafted, which is very suitable for rapid development of the interface ( http://www.layui. com/doc/ )

2. Front-end js code:

if($('.upload-img')[0]){
    layui.use('upload', function(upload){
      var avatarAdd = $ ('. avatar-add');
      layui.upload({
        elem: '.upload-img input'
        ,method: 'post'
        ,url: '/user/upload.do'
        ,before: function(){
          avatarAdd.find('.loading').show();
        }
        ,success: function(res){
          if(res.result){
            $.post('/user/set.do', {
              avatar: res.url
            }, function(res){
              location.reload();
            });
          } else {
            layer.msg(res.msg, {icon: 5});
          }
          avatarAdd.find('.loading').hide();
        }
        ,error: function(){
          avatarAdd.find('.loading').hide();
        }
      });
    });
  }

 3. Background receiving interface:

/**
	 * Avatar upload interface
	 * @param file upload image
	 * @param request
	 * @return
	 */
	@RequestMapping("/user/upload.do")
	@ResponseBody
	public Object upload(MultipartFile file, HttpServletRequest request) {
		try {
			String path = request.getSession().getServletContext().getRealPath("/");
			path = path + "/" +"data" + "/" + "upload" + "/" + "photo" + "/";
			LOGGER.info("path----------:{}", path);
			String image = UploadUtil.uploadImage(file, path) ;
			LOGGER.info("image-----------:{}", image);
			User user = (User)request.getSession().getAttribute("user") ;
			if(user != null) {
				user.setPhoto(image);
				userService.update(user);
				return renderResult(true, "Upload successful") ;
			}else {
				return renderResult(false, "User is not logged in, upload failed") ;
			}
		} catch (Exception e) {
			e.printStackTrace ();
		}
		return renderResult(false, "Upload failed") ;
	}

 Attach the upload photo tool class:

public static String uploadImage(MultipartFile file, String path) throws IOException {
		String name = file.getOriginalFilename() ;
		String suffixName = name.substring(name.lastIndexOf(".")) ;
		Date date = new Date() ;
		String hash = DateUtil.toStr(date.getTime());//Customize a name for the photo, use the time as the name, and will not repeat
		String fileName = hash + suffixName ;
		File tempFile = new File(path, fileName) ;
		if(!tempFile.getParentFile().exists()) {
			tempFile.getParentFile().mkdirs() ;
		}
		tempFile.createNewFile() ;
		file.transferTo(tempFile);
		return tempFile.getName() ;
	}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326437651&siteId=291194637