layui上传照片接口
程序员文章站
2022-06-08 21:44:22
...
1、layui(谐音:类UI) 是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织形式,门槛极低,拿来即用。其外在极简,却又不失饱满的内在,体积轻盈,组件丰盈,从核心代码到 API 的每一处细节都经过精心雕琢,非常适合界面的快速开发(http://www.layui.com/doc/)
2、前台js代码:
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、后台接收接口:
/** * 头像上传接口 * @param file 上传图片 * @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, "上传成功") ; }else { return renderResult(false, "用户未登录,上传失败") ; } } catch (Exception e) { e.printStackTrace(); } return renderResult(false, "上传失败") ; }
附上上传照片工具类:
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());//给照片自定义一个名字,用时间做名称,不会重复 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() ; }
上一篇: layui上传照片接口