[html] HTML - Display image after selecting filename

I have a form that allows me with

<input type="file" name="filename" accept="image/gif, image/jpeg, image/png">

to browse and select a file.

What I want to do is display that image immediately after the image has been selected. And this is before the "submit" button on the form has been pressed so the image almost certainly resides Client side. Can this be done?

This question is related to html file-upload

The answer is


You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/


This can be done using HTML5, but will only work in browsers that support it. Here's an example.

Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.