js+java 实现图片在线预览功能

本博客主要描述如何用JavaScript+java实现图片的预览功能,其实要点还是需要服务端的流。


(一)功能描述
点击页面的 【预览】 查看已经上传的或者在服务器中存在的图片。


(二)实现原理
使用img标签的src属性来渲染数据,但是,src的值是服务端返回的文件流。即是,点击【预览】按钮,跳转到预览页面,预览页面的img标签的src属性的值是经过渲染的文件流。


(三)具体的实现代码

  • (1)【预览】按钮页,需要传从服务端传来的路径
<html>
    <button id="yulanButton">预览</button>
    <script type="text/javascript">
        $(function(){
                $("#yulanButton").on('click', function(){
                    // 打开预览页面,需要传服务器的路径(url传值,可参考我的另一篇博客《js url传参》)
                    window.open('./yulan.jsp?url=获取到的服务器的路径');
                })
            })
        })
    </script>
</html>
  • (2) yulan.jsp 预览页面,需要连接到获取图片留的jsp
<div class="imgdiv">
    <img id="imgss" src="../params/projAndDetailImg.jsp" title="在线预览">
</div>
<script type="text/javascript">
    var yulanUrl = 获取到的服务器的路径
    $(function(){
        $("#imgss").attr('src', "../params/projAndDetailImg.jsp?photoUrl="+yulanUrl)
    });

</script>
  • (3) projAndDetailImg.jsp 服务端渲染页面
<%

    String photoUrl=request.getParameter("photoUrl");
    // photoUrl为接收到的路径
    if(StringUtils.isNotBlank(photoUrl)){
        File file = new File(photoUrl);
        // File file=new File(photoUrl);
        if (file.exists()) {
            try (FileInputStream fis = new FileInputStream(file);
                    BufferedInputStream bis = new BufferedInputStream(fis, 1024);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);) {
                byte[] cache = new byte[1024];
                int length = 0;
                while ((length = bis.read(cache)) != -1) {
                    bos.write(cache, 0, length);
                }
                /**
                return bos.toByteArray();
                BASE64Encoder encoder = new BASE64Encoder();
                return encoder.encode(bos.toByteArray());
                **/
                response.getOutputStream().write(bos.toByteArray());
            }
        }
    }
%>

ok !!!


图片在先预览功能相对于前端来说,不是有多复杂,只需要一个img标签即可,但是需要我们在jsp页面经过<%%>服务端渲染出一个文件路径流,方能访问到该图片地址。


方法,千千万,这只是其一。


源代码文件路径

https://github.com/mcya/JavaScriptExperience/issues

猜你喜欢

转载自blog.csdn.net/genius_yym/article/details/78134176