zoukankan      html  css  js  c++  java
  • 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工具类中的方法

  • 相关阅读:
    L1-046. 整除光棍
    L2-014. 列车调度
    L2-009. 抢红包
    L2-005. 集合相似度
    L2-021. 点赞狂魔
    L1-033. 出生年
    设计模式之生成器模式
    设计模式之抽象工厂模式
    设计模式之工厂方法模式
    设计模式之简单工厂模式
  • 原文地址:https://www.cnblogs.com/huxiaoguang/p/15066536.html
Copyright © 2011-2022 走看看