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();
                }
            }
        }
    }

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

你可能感兴趣的:(java)