Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Can not get value from onload properties of FileReader

filereader onload value

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1 Ehsan0101

Ehsan0101

    CC Regular

  • Member
  • PipPipPip
  • 38 posts

Posted 12 August 2014 - 07:31 PM

Hello,

I have a file type input element that receive multiple images:
---------------------------------------------

---------------------------------------------


I want to get base64 string from every image and want to return a json data. here js is code:
---------------------------------------------

function getPhotos() {
    var inp = document.getElementById('fileElementId');
    var photos = [];
    for (var i = 0; i < inp.files.length; ++i) {
        var obj = new Object();
        obj.name= inp.files.item(i).name;
        reader = new FileReader();
        reader.onload = function (e) {
            obj.base64 = reader.result;
        }
        reader.readAsDataURL(inp.files.item(i));
        photos.push(obj);
    }
    return photos;
}

--------------------------------------------------------


Main problem is the reader.onload section. If I use this:
------------------------------------------------
reader.onload = function (e) {
    console.log(reader.result);
}
------------------------------------------------


that's works fine into console and I can see base64 string value of every image. But If i use this:
--------------------------------------------

reader.onload = function (e) {
    obj.base64 = reader.result;
}
//OR this code,
var base64 = "";
reader.onload = function (e) {
    base64 = reader.result;
}
obj.base64 = base64;

Both of above are not get image base64 type string value. How can I return value from onload properties? Without onload section everything is working perfectly.

Thanks for reading with patience.


Edited by dargueta, 19 August 2014 - 09:28 AM.
Added code tags


#2 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts

Posted 17 August 2014 - 10:08 AM

You can flag the onload occurred.

Also, the problem seems to be the obj var. Did you try to put the result into a var only? without jumping to the object var later?



#3 dargueta

dargueta

    I chown trolls.

  • Moderator
  • 4854 posts

Posted 19 August 2014 - 09:30 AM

Could be a syntax error problem. You're missing a semicolon after you assign the function to reader.onload.

reader.onload = function (e) {
    base64 = reader.result;
}; // You need the semicolon here.

sudo rm -rf / && echo $'Sanitize your inputs!'





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download