1
element.bind('change', function () {

                var file = element[0].files[0];
                console.log(file);
                var reader = new FileReader();
                var url1 = reader.readAsDataURL(file);
                console.log(url1);
            });

I have used this in my directive. When I console file it displays file name, last modified date etc. But when I console url1 it is showing undefined. How can I get image url using file reader. Thank you.

1 Answer 1

1

You should check reader object instead of assigning it to a variable:

element.bind('change', function () {
    var file = element[0].files[0];
    console.log(file);
    var reader = new FileReader();
    reader.readAsDataURL(file);
    console.dir(reader);
    });

Result:

FileReader    error    :    null
onabort    :    null
onerror    :    null
onload    :    ƒ (e)
onloadend    :    null
onloadstart    :    null
onprogress    :    null
readyState    :    2
result    :    "data:image/png;base64,iVBORw0K[...]
Sign up to request clarification or add additional context in comments.

3 Comments

JSFiddle, check it again, its not the same... clue: two last lines
Thank you. Can you know the reason why it hasn't worked when I set the result to url1? Knowing the reason will be very helpful.
I think that it has something to do with the onload function, which is asynchronous. If you check console you'll see that it takes a while to appear the result so using reader.onload = function(){[Here you'll have the value]);};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.