赞
踩
用户上传头像流程
@PostMapping("upload") public String uploadHeader(MultipartFile headerImage, Model model) { //判断图片是否为空 if (headerImage == null) { model.addAttribute("error", "请先上传图片!"); return "/site/setting"; } //判断图片是否合法 String fileName = headerImage.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".")); if (!suffix.equals(".png") && !suffix.equals(".jpg") && !suffix.equals(".jpeg")) { model.addAttribute("error", "请上传png/jpg/jpeg格式的图片文件!"); return "/site/setting"; } //生成随机文件名 fileName = CommunityUtil.generateUUID() + suffix; //确定文件存放路径 File dest = new File(headerPath + "/" + fileName); //存储文件 try { headerImage.transferTo(dest); } catch (IOException e) { logger.error("文件存储失败" + e.getMessage()); throw new RuntimeException("文件存储失败,服务器异常", e); } //更新hostHoler中的url User user = hostHolder.getUser(); /* domain:服务器地址 */ String headerUrl = domain + contextPath + "/user/header/" + fileName; //更新数据库中的url userService.updateUserHeader(user.getId(), headerUrl); return "redirect:/index"; }
@GetMapping("/header/{fileName}") public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response) { //找到服务器存放路径 fileName = headerPath + "/" + fileName; //解析文件后缀 String suffix = fileName.substring(fileName.lastIndexOf(".")); //响应的格式 response.setContentType("image/" + suffix); try (FileInputStream stream = new FileInputStream(fileName); ServletOutputStream os = response.getOutputStream();) { byte[] buffer = new byte[1024]; int b = 0; while ((b = stream.read(buffer)) != -1) { os.write(buffer, 0, b); } } catch (IOException e) { logger.error("读取头像失败", e); } }
从url中解析出图片在服务器中存储的位置,将其转化为字节流,创建buffer(缓冲区)将二进制图片通过response上传至客户端(-1时代表结束)。
read:Reads up to b.length bytes of data from this input stream into an array of bytes.
write:Writes len bytes from the specified byte array starting at offset off to this output stream.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。