欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

web项目通过IO流读图片遇到错

程序员文章站 2022-06-16 20:16:38
...

之前写的用IO流给前端读取图片,本地测试、刚上linux时都没问题,过了几天读不出来了,神奇,但是另一个老大哥写的却一直没问题,问了一个大神,说可能是jdk版本问题,本机用的是sun的,linux环境用的是IBM的,姑且认为是这样吧
我的写法:

@RequestMapping(value = "getImage", method = RequestMethod.GET)
    public void getImage(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.info("getImage param:" + fileName);
        if(fileName == null || "".equals(fileName)) {
            throw new ServiceException("参数不正确!");
        }
        String imgFile = imagesPath + "/" +fileName;
        String imgType = fileName.substring(fileName.indexOf('.') + 1 , fileName.length());
        response.setDateHeader("Expires", 0);  
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");  
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");  
        response.setHeader("Pragma", "no-cache");  

        response.setContentType("image/"+imgType); 

        BufferedImage bi = null;
        ServletOutputStream out = response.getOutputStream();

        try {
            bi = ImageIO.read(new File(imgFile));
            ImageIO.write(bi, imgType, out);  
        } catch (IIOException e) {
            logger.error("读取不出图片:"+imgFile, e);
            bi = StringHelper.getCrystalImage(1, 1);
            ImageIO.write(bi, "png", out);
        } finally {
            try {  
                out.flush();
            } finally {  
                out.close();  
            }  
        }
    }

正确无误的写法

@RequestMapping(value = "/getImage", method = RequestMethod.GET)
    public void getImage(HttpServletResponse response,String fileName){

        if(!StringUtils.hasText(fileName)){
            return;
        }

        fileName = fileName.trim();

        if(fileName.length()<9){
            return;
        }

        File file = new File(portalnewsPath,fileName);

        if(!file.exists()){
            return;
        }

        ServletOutputStream sos = null;

        InputStream is = null;

        try {
            sos = response.getOutputStream();
            is = new FileInputStream(file);
            sos.write(IOUtils.toByteArray(is));
        } catch (Exception e) {
            logger.error("渲染图片出错", e);
        } finally {

            if (is != null) {
                try {
                    is.close();
                } catch (Exception e) {
                    logger.error("关闭图片读取流出错", e);
                } finally {
                    is = null;
                }
            }

            if (sos != null) {
                try {
                    sos.close();
                } catch (Exception e) {
                    logger.error("关闭响应输出流出错", e);
                } finally {
                    sos = null;
                }
            }
        }

    }

由此可见,往往越原始的写法越可靠

相关标签: io流 图片 web