js File 转 Base64 图片预览

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>图片预览</title>
        <style type="text/css">
            .global {
                width: 100%;
                height: 100%;
                display: flex;
                justify-content: center;
            }
            .count {
                width: 1000px;
                height: 300px;
                border: 2px solid deepskyblue;
                display: flex;
                justify-content: space-around;
                align-items: center;
            }
            .count div{
                width: 30%;
                height: 50%;
                border: 1px solid fuchsia;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            .count div img{
                height: 70%;
            }
            input {
                display: block;
            }
        </style>
    </head>
    <body>
        <div class="global">
            <div class="count">
                <div>
                    <input type="file" name="file" id="file">
                    <img src="" alt="" id="imgs">
                </div>
            </div>
        </div>
        <script type="text/javascript">
            // 文件类型转换
            // File 转 Base64 图片预览
            const fileToBase64 = (file, callback) =>{
                const reader = new FileReader()
                reader.onload = function(evt){
                   if(typeof callback === 'function') {
                        callback(evt.target.result)
                    } else {
                        console.log("我是base64:", evt.target.result);
                    }

                }
                /* readAsDataURL 方法会读取指定的 Blob 或 File 对象
                ** 读取操作完成的时候,会触发 onload 事件
                *  result 属性将包含一个data:URL格式的字符串(base64编码)以表示所读取文件的内容。
                */ 
                reader.readAsDataURL(file);
            }
            // 
            
            let _files = document.getElementById('file')
            _files.addEventListener('change',function(e){
                console.log(e.target.files[0])
                let file = e.target.files[0] // file对象
                const base64 = fileToBase64(file,base64 => {
                    let imgs = document.getElementById('imgs')
                    imgs.src = base64
                })
            })
            
            
        </script>
    </body>
</html>

 

posted @ 2021-07-26 14:57  live丶  阅读(489)  评论(0编辑  收藏  举报