0

I'm having (probably) easy issue to fix but can't figure it out myself. Basucally my reader.width and reader.height keep saying undefined :/.. everything else works as supposed to

function handleFileSelect(evt, selector) {

    var f = evt.target.files[0];
    var reader = new FileReader();

    reader.onload = (function(theFile) {
    return function(e) {
        var imgW = reader.width;
        var imgH = reader.height;
        console.debug("width: "+imgW); // undefined
        console.debug("height: "+imgH); // undefined
        var thumbHtml = ['<span><img class="thumb" src="', e.target.result,
                        '" title="', escape(theFile.name), '"/></span>'].join('');
        $(selector).parent().siblings('.previewThumb').html(thumbHtml);
        $(selector).parent().siblings('.previewThumb').removeClass('hidden')

    };
    })(f);

    // Read in the image file as a data URL.
    reader.readAsDataURL(f);
    $(selector).siblings('.list').html('<span>'+escape(f.name)+'</span></span>');
}

I tried alsoe.width and theFile.width - all of them return undefined :/

I tried to google but according to everything I have read reader.width should work

Appreciate the help

Cheers, Tom

Tomasz Golinski
  • 743
  • 5
  • 25

1 Answers1

2

FileReader itself doesnt have a width propery. The result from it contains only the raw image data. This has to be loaded as an Image before you can read the width. So you'd need to onload handlers 1) for the file to load 2) for the image to load.

Try something like this

function handleFileSelect(evt, selector) {

    var f = evt.target.files[0];
    var reader = new FileReader();

    reader.onload = function(e) { 
        // at this point we have the raw data. now we 
        // create an image out of it
        var image = new Image();
        image.src = e.target.result;

        image.onload = function() {
          // now we have the image.
          var imgW = image.width;
          var imgH = image.height;
          console.debug("width: "+imgW);
          console.debug("height: "+imgH);

          // we can insert image directly into DOM
          var thumb = $(image).addClass("thumb");
          $(selector).parent().siblings('.previewThumb').empty().append(thumb);
          $(selector).parent().siblings('.previewThumb').removeClass('hidden');
        };
    };

    // Read in the image file as a data URL.
    reader.readAsDataURL(f);
    $(selector).siblings('.list').html('<span>'+escape(f.name)+'</span></span>');
}
z33m
  • 5,993
  • 1
  • 31
  • 42