美文网首页
SpringMVC从数据库获取图片传递到页面

SpringMVC从数据库获取图片传递到页面

作者: Hiseico | 来源:发表于2018-07-03 14:59 被阅读0次

    整体思路:从数据库中读取图片二进制流并保存在InputStream中,通过ByteArrayOutputStream将InputStream转换到byte数组中并传递到页面。

        /**
         * 显示png图片 (文件下载)
         * @param pdId
         * @return
         */
        @RequestMapping("/processDefinitionAction_showImg")
        public void showImg(HttpServletResponse httpServletResponse, String pdId) throws IOException {
                //从数据库中获取流程图的二进制数据
                InputStream inputStream=processDefinitionService.findImgStream(pdId);
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100]; //buff用于存放循环读取的临时数据
            int rc = 0;
            //将输入流转换为字符数组输出流
            while ((rc = inputStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] img = swapStream.toByteArray(); //in_b为转换之后的结果
    
            //设置响应头
            //httpServletResponse.setHeader("content-type", "image/png;charset=UTF-8");
            httpServletResponse.setContentType("image/png");
            OutputStream os = httpServletResponse.getOutputStream();
            os.write(img);
            os.flush();
            os.close();
        }
    

    相关文章

      网友评论

          本文标题:SpringMVC从数据库获取图片传递到页面

          本文链接:https://www.haomeiwen.com/subject/dloduftx.html