Java实现将本地磁盘上的图片显示在img中?

上篇文章写到:基于maven的图片上传,这篇文章将介绍如何将上传后的图片显示出来!(我上传的图片在E:\test\文件夹下)具体代码如下:

public static final String IMG_DIR = "E:"+File.separator+"test"+File.separator;
@RequestMapping("/getAvatar/{id}")
    public void getAvatar(@PathVariable("id") String id, HttpSession session, HttpServletResponse response) {
        FileInputStream fis = null;
        ServletOutputStream outputStream = null;
        User user1 = userService.selectById(id);
        String imgName = user1.getAvatar();
        if (imgName == null) {
			imgName = IMG_DIR+"qq.jpg";
		}
        try {
            File imgFile;
            if (StringUtils.isNotEmpty(imgName)) {
                outputStream = response.getOutputStream();
                User user = (User) session.getAttribute("user");
                imgFile = new File( imgName);
                if (!imgFile.exists()) {
                    imgFile = new File(imgName);
                }

            } else {
                imgFile = new File(imgName);
            }
            //System.out.println(imgFile);
            fis = new FileInputStream(imgFile);
            byte[] b = new byte[1024];
            while ((fis.read(b)) != -1) {
                outputStream.write(b);
            }
        } catch (IOException e) {
            logger.error("{}", e);
        } catch (Exception e) {
            logger.error("{}", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

具体逻辑以及图片路径、名称,请根据自己的存储路径修改!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值