views:

239

answers:

5

I have an <input type="file"> where user selects an image file. Is it possible to show this image on a page without actually uploading it to the server first? Basically what I want to do is use the local file from the user's computer.

PS - I am using JQuery.

+3  A: 

No, this isn't possible. Javascript has no access to the local file system.

What you are asking for is a huge security risk disguised as a 'feature request'. If it was possible, then javascript could also open other kind of files from the local computer. MS Word documents for example - you know files that can run scripts.

kgiannakakis
Javascript doesn't but couldn't an IMG tag referencing the file system work? It certainly does from a static page.
Lazarus
That would work, IF you could get the local path of the file using javascript.
kgiannakakis
+4  A: 

It is impossible, even referencing to file using file:// won't work as when you get the value from the file input box, you only get the filename, not the path. So it's impossible to know where the image is located. To make it work, you'd have to use a Flash based uploader.

This is surely a safety measure, as Internet Explorer does give you a path, only thing is that it is always c:\fakepath\filename.png. I guess the browsers are doing their job preventing JavaScript from getting any meaningful information from the filesystem.

The return values for different browsers when trying to upload file C:\test.txt:

  • Firefox 3.5.6
    test.txt

  • Chrome 3.0.195.38
    test.txt

  • Opera 10.00
    C:\fake_path\test.txt

  • Internet Explorer 8
    C:\fakepath\test.txt

Tatu Ulmanen
+1  A: 

It is not reliably possible in Javascript. It is possible using Flash-based uploaders like this one.

Pekka
A: 

:-), I think it is pretty easy.

document.getElementByid('img1').src = document.getElementById('fileUpload').value;

but this is not possible in all browsers

Ravia
This won't work for the reasons that Tatu Ulmanen mentioned.
niaher
A: 

It IS possible in Internet Explorer, however your user has to add your site to "Trusted Sites", or C:\fakepath\ is all you'll see. Once added to trusted sites you get access to the real path.

Don't expect to find a great cross-browser solution to this!

Greg Lyon