在SpringBoot通常上傳圖片,需要用到OSS或上傳到指定的目錄下通過域名解析來訪問靜態資源,不想那么麻煩的,只是顯示用戶上傳頭像的沒必要搞那么麻煩,於是就想到通過圖片流來讀取圖片並顯示在瀏覽器上
@Autowired private AdminService adminService; @RequestMapping( value = "avatar", method = RequestMethod.GET, headers = "Accept=application/json") public void getAvatar(HttpServletResponse response) throws IOException { Admin admin = (Admin) session.getAttribute("admin"); Admin result = adminService.getUserInfo(admin.getUserId()); ServletOutputStream outputStream = null; InputStream inputStream = null; try { String imgPath = result.getAvatar(); if(StrUtil.isEmpty(imgPath)) { ClassPathResource classPathResource = new ClassPathResource("/static/admin/img/logo.png"); inputStream = classPathResource.getInputStream(); }else{ inputStream = FileUtil.getInputStream(imgPath); } response.setContentType("image/png"); outputStream = response.getOutputStream(); int len = 0; byte[] buffer = new byte[4096]; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { outputStream.close(); inputStream.close(); } }
其中FileUtil.getInputStream 是HuTool中IO工具類中的方法