Select 并且在 FileReader 不工作的情况下显示图像

Select and Display Image with FileReader Not Working

我有一个表单,用户可以选择先 select,然后再上传图片。 selected 图像应在下面的图像标记中预览。

我的HTML设置(只有必要的部分):

<div class="form-group">
            <label for="">Image</label>
            <input type="file" accept="image/*" name="image" id="selImg" class="form-control" onchange="showImage().call(this)">
            <img src="#" id="imgPreview" style="display: none; height: 200px; width: 200px">
        </div>

我在下面有一个脚本标签,我正在编写我的函数来渲染 selected 图像,如下所示:

<script>

        function showImage (){
            if (this.files && this.files[0]){
                let r = new FileReader();
                r.onload = ((data) => {
                   let img = document.getElementById("imgPreview");
                   img.src = data.target.result;
                   img.style.display = "block";
                });
                r.readAsDataURL(this.files[0]);
            }
        }

        // tried previously but still doesnt work
        // function readURL(inputStr){
        //     if (inputStr.files && inputStr.files[0]){
        //         let fileReader = new FileReader();
        //         fileReader.onload = (data)=> {
        //             $('#imgPreview').attributes('src', data.target.result).width(100).height(100);
        //         }
        //         fileReader.readAsDataURL(inputStr.files[0]);
        //     }
        // }
        //
        // $('#img').change( ()=>{
        //     console.log(`Image Clicked`);
        //     readURL(this);
        // });

    </script>

未注释的代码不是我的,而是来自教程 - this tutorial 但也不起作用。

谁能解释一下为什么图片不显示? 非常感谢。

call 是一个函数的方法。如果您在函数末尾附加 (),您将对函数的 return 而不是函数本身进行操作。
因此你的代码应该是

showImage.call(this)