java web读取显示图片

一般读取显示图片最简单的是在标签中的src属性中直接写图片地址,但是这样的话会暴露图片存放目录,因此可以让请求通过controller写回流的方式进行显示。
controller:

@RequestMapping(value = "getImage", method = RequestMethod.GET)
    public void getImage(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        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.info("读取不出图片:"+imgFile, e);
            bi = StringHelper.getCrystalImage(1, 1);   //如果没有该文件,则显示默认的透明图片
            ImageIO.write(bi, "png", out);
            throw new ServiceException("读取不出图片");   //ServiceException是自己定义的异常,可忽略。
        } finally {
            try {  
                out.flush();
            } finally {  
                out.close();  
            }  
        }
    }

显示默认图片方法:

public static BufferedImage getCrystalImage(Integer width, Integer height){
        width = width==null?710 : width; 
        height = height == null ? 285: height; 

        // 创建BufferedImage对象 
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 

        // 获取Graphics2D 
        Graphics2D g2d = image.createGraphics(); 
        // ---------- 增加下面的代码使得背景透明 ----------------- 
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); 
        g2d.dispose(); 
        g2d = image.createGraphics(); 
        // ---------- 背景透明代码结束 ----------------- 
        // 画图 
        g2d.setColor(Color.WHITE); 
        g2d.setStroke(new BasicStroke(1)); 
        //释放对象 
        g2d.dispose();

        return image;
    }

同理,下载文件也可以通过流的方式写回去

public void downloadFile(String fileName, HttpServletRequest request, HttpServletResponse response) {
        String filepath = attachmentPath + "/" + fileName;
        String downloadName = fileName;

        File file = new File(filepath);
        FileInputStream inputStream = null;
        ServletOutputStream outputStream = null;
        byte[] b = new byte[1024];
        int len = 0;
        try{
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();

            response.setContentType("application/force-download");
            String downloadFileName = null;
            String agent = (String)request.getHeader("USER-AGENT");
            if(agent!=null && agent.toLowerCase().indexOf("firefox") >0) {
                downloadFileName = "=?UTF-8?B?" + (new String(Base64.encode(downloadName.getBytes("UTF-8")))) + "?=";
            }else if(agent!=null && (agent.toLowerCase().indexOf("msie") >0 || agent.toLowerCase().indexOf("trident") >0)){
                downloadFileName = URLEncoder.encode(downloadName,"UTF-8");
                downloadFileName = downloadFileName.replaceAll("\\+", "%20");
            }else{
                downloadFileName = new String(downloadName.getBytes("UTF-8"),"ISO-8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
            response.setContentLength((int) file.length());
            while((len = inputStream.read(b)) != -1) {
                outputStream.write(b,0,len);
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            if(inputStream != null) {
                try{
                    inputStream.close();
                    inputStream = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值