Using $(this) with FileReader() to target result

馋奶兔 提交于 2019-12-03 04:04:51

I had never worked with this API before. Interesting stuff.

This version loops through all the file inputs and loads their preview images. The function is triggered by a button click.

$(function(){
    $("#btnLoadPreviews").click(loadPreviews_click);
})

function loadPreviews_click(e) {
    $(".image").each(function() {
        var $input = $(this);
        var inputFiles = this.files;
        if(inputFiles == undefined || inputFiles.length == 0) return;
        var inputFile = inputFiles[0];

        var reader = new FileReader();
        reader.onload = function(event) {
            $input.next().attr("src", event.target.result);
        };
        reader.onerror = function(event) {
            alert("I AM ERROR: " + event.target.error.code);
        };
        reader.readAsDataURL(inputFile);
    });
}

If you prefer to have the preview image load as they are selected you could use this version instead.

$(function(){
    $(".image").change(showPreviewImage_click);
})

function showPreviewImage_click(e) {
    var $input = $(this);
    var inputFiles = this.files;
    if(inputFiles == undefined || inputFiles.length == 0) return;
    var inputFile = inputFiles[0];

    var reader = new FileReader();
    reader.onload = function(event) {
        $input.next().attr("src", event.target.result);
    };
    reader.onerror = function(event) {
        alert("I AM ERROR: " + event.target.error.code);
    };
    reader.readAsDataURL(inputFile);
}

This is how I would do it. Assign the target to the reader object itself and use it later.

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        // set where you want to attach the preview
        reader.target_elem = $(input).parent().find('preview');
        reader.onload = function (e) {
           // Attach the preview
           $(reader.target_elem).attr('src', e.target.result);
        };

        reader.readAsDataURL(input.files[0]);
    }
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!