java servlet 读取图片 相应

来源:互联网 发布:五毒萝莉捏脸数据截图 编辑:程序博客网 时间:2024/05/18 14:24

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
    {
        int bateMax = 5000;
        String url = req.getParameter("url");
       
        if (StringTools.isNullOrNone(url))
        {
            return;
        }
       
        // 获取图片后缀名的开始下标
        int imgSuffixIndex = url.lastIndexOf(".");
       
        // 获取配置的图片格式
        String imgSuffixFormat = url.substring(imgSuffixIndex + 1);
       
        ServletOutputStream sos = null;
        InputStream in = null;
        BufferedInputStream bis = null;
        try
        {

          
                  in = new FileInputStream(url);
            // 将图片读成流
            resp.setContentType("image/" + imgSuffixFormat);
            resp.setHeader("Parama", "no-cache");
            resp.setHeader("Cache-Control", "no-cache");
            resp.setDateHeader("Expires", 0);
            sos = resp.getOutputStream();
            bis = new BufferedInputStream(in);
            byte[] temp = new byte[bateMax];
            int len = 0;
            while (-1 != (len = bis.read(temp)))
            {
                sos.write(temp, 0, len);
            }
           
            sos.flush();
        }
        catch (IOException e)
        {
            // 日志流读取错误
            log.error(e, e);
        }
        finally
        {
            try
            {
                if (null != bis)
                {
                    bis.close();
                   
                    bis = null;
                }
            }
            catch (IOException e)
            {
                log.error(e, e);
            }
           
            try
            {
                if (null != in)
                {
                    in.close();
                   
                    in = null;
                }
            }
            catch (IOException e)
            {
                log.error(e, e);
            }
           
           
        }
       
    }