views:

1521

answers:

4

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?

+1  A: 

Here's a jQuery + PHP script for uploading an image an previewing it.

Jamis Charles
this one uploads the image before showing it. neat code, though
Javier
I was trying to avoid the upload first, but it looks like this is gonna be the way to go. I just have to come up with something AJAXy to handle multiple images/previews.
Matt Van Horn
+1  A: 

JavaScript has no access to the local file system for security purposes, period.

Diodeus
It's security idiocy. Such file cannot be send to server, so what is this for? I have seen many web-games that have possibility to download graphics onto your hdd, so game works faster.
Thinker
Thinker, that's typically accomplished with HTTP caching - that's a totally different thing. JS still doesn't have access to paths on the client filesystem.
DDaviesBrackett
+1  A: 

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 with file:// source URLs, if the user's browser allows the file:// 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.

DDaviesBrackett
zeroin23
A: 

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.

Dietrich Epp