Get image data from client side using javascript

Well, I had a requirement to show a preview of image, whenever client selects an image inside a form. First I thought it was just a easy task… But it really took about one hour of me to figure the way out…

As it was an input element with type=file, I simply tried to get the value and push it to an image element’s source attribute attaching ‘file://’ at the beginning. But life’s not that easy! The value only returns the file name not the full path. How can I get the full path??!! I can see the path on the input box, but I can’t get it!!!

Next approach, go to our best friend, Google! Well, I guess she wasn’t very pleased with me and didn’t help me very much…

Now what?! Well, let’s try the DOM inspector of Firefox. There I found three functions for the file input element.

  • getAsBinary()
  • getAsDataURL()
  • getAsText()

They are all self explanatory… My head was already stuck at that moment. So I didn’t see the ‘Data URL’ function first. Tried to parse binary for a while. But couldn’t find a way to push the binary data of an image inside the image tag. Then I noticed the next function. Well, it worked like a charm. I just pushed the function’s return value to the image tag’s source attribute. Done.

So, to get the file path, the call should be like:

file_input_element_id.files[0].getAsDataURL()

That’s all… :-)

N.B. For IE, it works OK with adding the ‘file://’ before the value of input element. You just need to have proper permission level.

5 Responses to “Get image data from client side using javascript”

  • Hello, I came across this post while searching for help with JavaScript. I’ve recently changed browsers from Google Chrome to Microsoft IE 6. Just recently I seem to have a problem with loading JavaScript. Everytime I go on a website that needs Javascript, my computer does not load and I get a “runtime error javascript.JSException: Unknown name”. I can’t seem to find out how to fix the problem. Any help is greatly appreciated! Thanks

  • Rony says:

    Actually IE6 is a really old browser and I’d suggest you to switch to Firefox or at least latest IE8. A lot of JavaScript and CSS features aren’t supported by IE6 and if you are aware, most of the web applications are now closing their support for IE6. Even Microsoft is asking their users to upgrade the browser. :)

  • Jason says:

    The getAsDataURL() function does not work in Chrome 5.x right now :\

  • Rony says:

    I haven’t tested on Chrome. Will check if there is any alternative for chrome when I get a minute :)

  • Yogesh says:

    Its not working in Google Chrome
    no method found getAsDataURL()

Leave a Reply

About

Name: Ashiqur, aka "rony"

Bio: I'm Rony. Graduated in CSE. Took programming as profession. Right now working as CEO of Creash.

Search
Categories