• Spring Boot 通过流读取图片并显示在浏览器中


    在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工具类中的方法

  • 相关阅读:
    chromedriver安装与配置(ubuntu linux下)
    Ajax 通信技术--hidden Frame GET 请求 和 POST 请求
    photoshop去除图片上的水印
    redis和memcache的对比
    关于mongodb ,redis,memcache之间见不乱理还乱的关系和作用
    MYSQL中'TYPE=MyISAM'错误的解决方案
    http协议
    jQuery常用方法
    SQL Server中行列转换 Pivot UnPivot
    jQuery插件开发
  • 原文地址:https://www.cnblogs.com/huxiaoguang/p/15066536.html
Copyright © 2020-2023  润新知