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

posted @ 2021-07-27 16:21  小武汉  阅读(2835)  评论(0编辑  收藏  举报