【问题标题】:Select and Display Image with FileReader Not Working在 FileReader 不工作的情况下选择并显示图像
【发布时间】:2018-03-02 14:13:47
【问题描述】:

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

我的 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>

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

<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,但也不起作用。

有人可以向我解释为什么不显示图像吗? 非常感谢。

【问题讨论】:

    标签: javascript html image filereader


    【解决方案1】:

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

    showImage.call(this)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 2015-02-23
      • 2018-08-13
      • 2012-08-02
      • 2012-05-29
      • 2011-12-17
      • 2010-11-18
      • 2019-10-26
      相关资源
      最近更新 更多