html5动态加载图片 reader.onload

靳金鹏
2023-12-01

完整代码:

<script type="text/javascript">
    function ProcessFile(e) {
        var file = document.getElementById('file').files[0];
        if (!/image\/\w+/.test(file.type)) {
            file = NaN
            alert("看清楚,这个需要图片!");
        }
        {#document.getElementById("result").removeChild( document.getElementsByTagName("img")[0] );#}
        if (file) {
            var reader = new FileReader();

            reader.onload = function (event) {

                var txt = event.target.result;
                var img = document.createElement("img");
                img.src = txt;//将图片base64字符串赋值给img的src
                // console.log(txt);
                img.width = 540;
                var div = document.getElementById("result");
                div.innerHTML = "";
                div.appendChild(img);

            };
        }
        reader.readAsDataURL(file);
    }

    function contentLoaded() {
        document.getElementById('file').addEventListener('change',
            ProcessFile, false);
    }

    window.addEventListener("DOMContentLoaded", contentLoaded, false);
</script>
<form role="form" method="post" class="col-lg-6 "> 
   <div class="form-group">
       <label for="user_face">头像</label>
       <input type="file" id="user_face" name="user_face" class="form-control" >
   </div>
   <div id="result"></div>#onload图片
   <div class="form-group">        
      <input type="submit" class="btn btn-success" name="submit" value="确认">
   </div>
</form>
 类似资料: