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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM