【问题标题】:How to use HTML5 file reader onload method correctly如何正确使用 HTML5 文件阅读器 onload 方法
【发布时间】:2017-03-18 09:14:26
【问题描述】:

我正在创建一个文件上传器,其中用户使用文件输入一一选择图片,并使用 HTML 文件阅读器 API 将其添加到托盘(预览)中。 My problem is when the first picture is selected its added to the tray once correctly when the second photo is selected is added twice when the third is selected its added thrice.这意味着第 n 张照片的 n 个预览。我不知道做错了什么请帮忙。

我的代码

 //Event handler for image upload button click
   $('body').on('click', '#add-default-pic', function (event) {
    event.preventDefault();

    $('#default-pic-chooser').trigger('click');
    //Wait for #photo file input to change

    $('#default-pic-chooser').on('change', function () {
        if ($('#default-pic-chooser').val() !== '') {
            //Do checks to see if photo is valid
            if (isImage($('#default-pic-chooser').val())) {

            } else {

                $('.info').html('Sorry your picture format is not supported');
                $('#infoModal').modal();
                return;
            }
        }
        if (typeof (FileReader) != 'undefined') {
            reader = new FileReader();
            //Run this function when file is ready

            reader.onload = function (e) {
                img = e.target.result;
                $('.default-pics-area').append('<img src="' + img + '"  style="padding:0px; width:auto; height:auto; max-width:100%; max-height:150px;"/>');
                // alert("whats on:"+img);
                if ($('#default-pic-chooser').val() !== '') {

                    var route = base + '/pics/default/upload';
                    var photo = document.getElementById('default-pic-chooser').files[0]; //grapping photo file
                    // uploadPhoto(route,photo);
                    upload(route, photo, 'photo');
                }
            };
            //Trigger the onload function

            reader.readAsDataURL($(this) [0].files[0]);
        } else {
            alert('OOPS! you wont be able to preview your image because your browser does not support this feature...');
        }
    });
});

【问题讨论】:

    标签: javascript jquery html html5-filesystem


    【解决方案1】:

    $('#default-pic-chooser').on('change'....) 从正文的点击处理程序中删除。

    因为每次点击#add-default-pic,都会在#default-pic-chooser中添加一个新的change处理函数。所以,当你触发click时,会一一触发函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-19
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 2018-02-12
      相关资源
      最近更新 更多