spring mvc 通过字节流返回图像

/**
     * 通过url请求返回图像的字节流
     */
    @RequestMapping("icon/{cateogry}")
    public void getIcon(@PathVariable("cateogry") String cateogry,
                        HttpServletRequest request,
                        HttpServletResponse response) throws IOException {


        if(StringUtils.isEmpty(cateogry)) {
            cateogry = "";
        }


        String fileName = request.getSession().getServletContext().getRealPath("/")
                + "resource\\icons\\auth\\"
                + cateogry.toUpperCase().trim() + ".png";


        File file = new File(fileName);


        //判断文件是否存在如果不存在就返回默认图标
        if(!(file.exists() && file.canRead())) {
            file = new File(request.getSession().getServletContext().getRealPath("/")
                    + "resource/icons/auth/root.png");
        }


        FileInputStream inputStream = new FileInputStream(file);
        byte[] data = new byte[(int)file.length()];
        int length = inputStream.read(data);
        inputStream.close();


        response.setContentType("image/png");


        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
    }

猜你喜欢

转载自blog.csdn.net/ch5057997/article/details/78650037
今日推荐