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();
    }

原文地址:http://www.cnblogs.com/Dtscal/archive/2013/02/01/2889080.html

你可能感兴趣的:(SpringMVC)