zoukankan      html  css  js  c++  java
  • spring mvc 通过字节流返回图像

    需求:

    通过一个请求url返回一张图片

    例如

    这样有一个好处是,你发你的请求.但是你就是不知道我的实际图片在哪儿?呵呵好耍三

    代码

    View Code
     /**
         * 通过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();
        }
  • 相关阅读:
    eclipse常用快捷键
    Android 布局
    Android UI设计
    Android Context 是什么?
    内部类
    手写单例模式
    上课笔记:移动开发新利器-你好,Flutter
    Android Fragment
    Kotlin语言
    Android虚拟机和类加载机制
  • 原文地址:https://www.cnblogs.com/Dtscal/p/2889080.html
Copyright © 2011-2022 走看看