To be more specific, I want to use a form with one or more file input fields used for images. When those fields are changed, I'd like to show a preview of the associated image, before sending the data to the server.
I've tried a number of javascript approaches, but I always run into security errors. I wouldn't mind using java or flash, as long as the solution degraded gracefully for those users who didn't have them. (They wouldn't get previews, and they wouldn't get an annoying 'install this thing' either.)
Has anyone done this in a simple, reusable way?
P.S. I know there's a sandbox, but does the sandbox have to be in a dark, locked room with all the windows blacked out?
JavaScript has no access to the local file system for security purposes, period.
Here's a jQuery + PHP script for uploading an image an previewing it.
You can try this approach, although it seems it doesn't work on IE.
http://saravani.wordpress.com/2012/03/14/preview-of-an-image-before-it-is-uploaded/
It's simple and fast to code.
I put the code here just in case the source dies:
Script:
In the HTML:
The first step is finding out the image path. JavaScript is allowed to interrogate the upload control for a filename/path, but (for reasons of security) various browsers show different things to the JS engine than they display to the user - they tend to keep the filename intact so you can at least validate its extension, but you may get
c:\fake_path\
or some similarly obfuscated thing prepended to the filename. Trying this on various browsers will give you an idea as to what gets returned as a real path, and what gets faked out, and where.The second step is displaying the image. It's possible to display local images if you know their paths, via
img
tags withfile://
source URLs, if the user's browser allows thefile://
scheme. (Firefox doesn't, by default.) So if you can get the user to tell you what the full path to the image is, you can at least try to load it.I have only ever seen Java applets that do this, for example, the image uploading applet on Facebook. The downside to the Java approach is that the user will be prompted to trust the applet before it runs, which is a kind of annoyance, but this allows the applet to present a file browser with image previews or do more interesting things like allows the user to upload an entire directory.
No need for fancy stuff. All you need is the
createObjectURL
function, which creates a URL that can be used as the imagesrc
, and can come straight from a local file.Let's say you selected a couple of images from the user's computer using a file input element (
<input type="file" />
). Here's how you would create previews for image files for it: