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

file-upload, filereader, jquery

Solution

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);
}

Problem

I'm trying to show an ajax preview of an image from a file input. Easy enough using FileReader() but I'm using it with a loop so I when it's time to place the result inside an image source, I need to use $(this) to target the loop item of the input. That doesn't even make sense to me so here we go. We have a loop.. ``` <li> <input type="file" class="image" /> <img src="" class="preview" /> </li> <li> <input type="file" class="image" /> <img src="" class="preview" /> </li> <li> <input type="file" class="image" /> <img src="" class="preview" /> </li> ``` So now lets say the second input is choosen and now I need to add the result from FileReader to it's image src. How am I targeting the second loop item and its content to do stuff? ``` function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { // Here I need to use $(this) to target only the second list item's img.preview $('.preview').attr('src', e.target.result); }; reader.readAsDataURL(input.files[0]); } } ```

Original source