is it possible to preview local images before uploading them via a form?

Matt Van Horn picture Matt Van Horn · May 28, 2009 · Viewed 16.7k times · Source

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?

Answer

dev picture dev · Oct 3, 2011

No need for fancy stuff. All you need is the createObjectURL function, which creates a URL that can be used as the image src, 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:

function createObjectURL(object) {
    return (window.URL) ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}

function revokeObjectURL(url) {
    return (window.URL) ? window.URL.revokeObjectURL(url) : window.webkitURL.revokeObjectURL(url);
}

function myUploadOnChangeFunction() {
    if(this.files.length) {
        for(var i in this.files) {
            var src = createObjectURL(this.files[i]);
            var image = new Image();
            image.src = src;
            // Do whatever you want with your image, it's just like any other image
            // but it displays directly from the user machine, not the server!
        }
    }
}