您的位置:首页 > Web前端 > JQuery

jquery实现图片上传前本地预览功能

2017-08-09 08:49 961 查看
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  

<%  

String path = request.getContextPath();  

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  

%>  

  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  

<html>  

  <head>  

      

    <style type="text/css">  

        #pic{  

                width:100px;  

                height:100px;  

                border-radius:50%;  

                margin:20px auto;  

                cursor: pointer;  

                }  

    </style>  

  

    <script type="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>  

    <script type="text/javascript">  

    $(function() {  

            $("#pic").click(function () {  

                debugger;  

                $("#upload").click(); //隐藏了input:file样式后,点击头像就可以本地上传  

              

                $("#upload").on("change", function() {  

                    var objUrl = getObjectURL(this.files[0]); //获取图片的路径,该路径不是图片在本地的路径  

                        if (objUrl) {  

                            $("#pic").attr("src", objUrl); //将图片路径存入src中,显示出图片  

                    }  

                });  

            });  

    });  

  

    //建立一個可存取到該file的url  

    function getObjectURL(file) {  

        debugger;  

        var url = null;  

        if (window.createObjectURL != undefined) { // basic  

            url = window.createObjectURL(file);  

        } else if (window.URL != undefined) { // mozilla(firefox)  

            url = window.URL.createObjectURL(file);  

        } else if (window.webkitURL != undefined) { // webkit or chrome  

            url = window.webkitURL.createObjectURL(file);  

        }  

        return url;  

    }  

</script>  

  </head>  

    

  <body>  

    <img id="pic" src="" >  

    <input id="upload" name="file" accept="image/*" type="file" style="display:none"/>  

  </body>  

</html>  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: