Local Previews of Images from File Inputs (fail)

Avatar of Chris Coyier
Chris Coyier on

DigitalOcean provides cloud products for every stage of your journey. Get started with $200 in free credit!

A little while back there was a guest post about Ajax image previews. It’s a nice technique but it left myself and a few other commenters thinking: wouldn’t it be cool if you didn’t have to upload the image at all to preview it? After all, the image is on the persons computer already why can’t we just snag the local file path and use that as the src of an image.

Well, it’s that snagging of the file path that is the problem. I did some research and testing in different browsers and I thought I’d document the results.


The idea comes from the fact that you can see see the file path in the file input after you select it.

Your eyeballs can see it, but JavaScript cannot.

Security issue

In all my naivety, I just though “Hey we’ll just get the value of the input and use that as the src of an image element next to the input!” As I quickly learned, there are some security concerns with allowing the browser to see a local file path like that. A malicious script could learn a good deal about your local file system if a file input was willing to cough up data like that.

What browsers actually do

Internet Explorer & Opera

Both these browsers will return a value like this when trying to access the value of the file input:


This article has a bit more information on the subject. Apparently if you add the site in question to the “Trusted sites” list in Internet Explorer it will return the file path. But of course you can’t expect users to do that.

WebKit (Safari / Chrome)

Return no value whatsoever for the file input value.


Firefox is unique in that it returns only the filename for the file inputs value. While clearly that won’t work to get a local image preview working, this thread on StackOverflow lead to an interesting solution.

While it won’t give you the file path, Firefox will let you use a function called ‘getAsDataURL()’ on the files attribute of the DOM on that input.

// Browser supports `files` as part of DOM
if (this.files) {
   //  This works in Firefox, #image-preview is an <img src="" />
   $("#image-preview").attr("src", this.files[0].getAsDataURL());

View Demo (only Firefox does anything)