获取图片base64的方法

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <link rel="stylesheet" href="">
</head>
<body>
<input type="file" class="file" name="imgfile" id="imgfile" placeholder="请选择文件">
<img src="" id="showImg" >

<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var input = document.getElementById("imgfile");
//检测浏览器是否支持FileReader
 if (typeof (FileReader) === 'undefined') {
     result.innerHTML = "抱歉,你的浏览器不支持 FileReader,请使用现代浏览器操作!";
     input.setAttribute('disabled', 'disabled');
 } else {
 //开启监听
     input.addEventListener('change', readFile, false);
 }
function readFile() {
    var file = this.files[0];

     //限定上传文件的类型,判断是否是图片类型
     if (!/image\/\w+/.test(file.type)) {
         alert("只能选择图片");
         return false;
    }
     var reader = new FileReader();
     reader.readAsDataURL(file);
     reader.onload = function (e) {
       base64Code=this.result;
        //把得到的base64赋值到img标签显示
       $("#showImg").attr("src",base64Code);
     }
  }
</script>


</body>
</html>

猜你喜欢

转载自www.cnblogs.com/JeneryYang/p/8953775.html