Java Web浏览器打开图片(而不是下载)

因为一些原因,图片访问需要在项目中通过controller接口的形式访问,做这个的时候遇到一个问题:浏览器单独访问接口时会出现下载图片的现象,将接口链接放到img标签的src中就能直接显示。这对用户来讲是个不好的体验,网上找了很多文章,都没有说到这个,在试了很多种方法后,终于被我找到了方法,以下是代码:

    @RequestMapping("/image/test.jpg")
    public void image(HttpServletResponse response){
        InputStream is = null;
        OutputStream os = null;
        try {
            response.setContentType("image/jpeg");
            File file = new File("E:\\images\\test.jpg");
            response.addHeader("Content-Length", "" + file.length());
            is = new FileInputStream(file);
            os = response.getOutputStream();
            IOUtils.copy(is, os);
        } catch (Exception e) {
            log.error("下载图片发生异常", e);
        } finally {
            try {
                if (os != null) {
                    os.flush();
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                log.error("关闭流发生异常", e);
            }
        }
    }

最主要的是要加上image/jpeg(根据文件后缀名决定,png是image/png),但是不能是image/*,否则还是会出现下载图片的现象。其次是Content-Length(不加也可以实现打开图片)

你可能感兴趣的:(Java Web浏览器打开图片(而不是下载))