图片转base64上传

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div>
     <input type="file" id="imgTest" type="file" onchange="imgChange(event)" accept=".gif,.jpg,.jpeg,.png">
    </div>
    <img src="" id="showImage" alt="">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        function imgChange(e) {
        console.log();
        console.info(e.target.files[0]);//图片文件
        var dom =$("#imgTest")[0];
        console.info(dom.value);//这个是文件的路径 C:\fakepath\icon (5).png
        console.log(e.target.value);//这个也是文件的路径和上面的dom.value是一样的
        var reader = new FileReader();
        reader.onload = (function (file) {
            return function (e) {
               console.info(this.result); //这个就是base64的数据了
                $("#showImage")[0].src=this.result;
            };
        })(e.target.files[0]);
        reader.readAsDataURL(e.target.files[0]);
    }
    </script>
</body>
</html>

 

posted @ 2018-08-03 17:02  Jinsuo  阅读(130)  评论(0编辑  收藏  举报