【Java】web实现图片在线预览

一.场景还原

用户上传了一张图片,已有服务器保存路径,现由于系统配置无法直接通过图片URL打开预览图片,需实现点击预览将图片显示在浏览器上。

二.实现方法

html:

    <a href="##" onclick="preview('${file.filePath}')" >预览</a>

此处用预览按钮方法实现

Javascript:

function preview(path){
    var ext=path.split('.')[1];
    if(ext=="PNG"){
        window.open("<%=path%>/file/showImage.do?path="+path);
    }
}

此处因为测试判断了PNG

Java:

/*
     * 在线预览图片
     */
    @RequestMapping("/showImage.do")
    public @ResponseBody
    void showImage(String path) throws IOException {
        getResponse().setContentType("text/html; charset=UTF-8");
        getResponse().setContentType("image/jpeg");
        String fullFileName = getRealPath("/upload/" + path);
        FileInputStream fis = new FileInputStream(fullFileName);
        OutputStream os = getResponse().getOutputStream();
        try {
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = fis.read(buffer)) != -1)
                os.write(buffer, 0, count);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null)
                os.close();
            if (fis != null)
                fis.close();
        }
    }

三.执行结果

打开一个新的窗口,显示图片。

 

 

本文为博主原创文章

转载请保留出处:http://www.cnblogs.com/zwqh/p/6494839.html 
谢谢合作

posted @ 2017-03-03 10:13  朝雾轻寒  阅读(14170)  评论(0编辑  收藏  举报