spring从服务器磁盘读取图片,然后显示于前端页面上

需求是,前台通过传参,确定唯一图片,然后后台在服务器磁盘中读取该图片,然后显示于前台页面上。

后台代码:

@RequestMapping("unit/bill/showeinvoice")
@ResponseBody
    public void showEInvoice(HttpServletRequest request,       HttpServletResponse response){
        FileInputStream fis = null;
        OutputStream os = null;
        String filepath = path;     //path是你服务器上图片的绝对路径
            File file = new File(filepath);
            if(file.exists()){
                try {
                    fis = new FileInputStream(file);
                    long size = file.length();
                    byte[] temp = new byte[(int) size];
                    fis.read(temp, 0, (int) size);
                    fis.close();
                    byte[] data = temp;
                    response.setContentType("image/png");
                    os = response.getOutputStream();
                    os.write(data);
                    os.flush();
                    os.close();
                    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
    }

前台代码:

<html>
   <body>
         <img  src="/unit/bill/showeinvoice" />  //src值就是后台controller的映射地址
    </body> 
</html>    
原文地址:https://www.cnblogs.com/lovefaner/p/10150754.html