Is it possible to load an image into a web page locally?

278 Views Asked by At

The idea is to take an image from a user's machine and allow them to display the image in a webpage. I do not want to send the image back to the server.

An upload button will exist. It should just update the page content dynamically.

Can this be done with HTML5 localstorage or anything?

2

There are 2 best solutions below

0
On BEST ANSWER

FileReader is capable of doing this. Here's sample code:

<input type="file" id="files" name="files[]" multiple />
<img id="image" />

<script>
    function onLoad(evt) {
        /* do sth with evt.target.result - it image in base64 format ("data:image/jpeg;base64,....") */
        localStorage.setItem('image', evt.target.result);
        document.getElementById('image').src = evt.target.result;
    };

    function handleFileUpload(evt) {
        var files = evt.target.files; // FileList object

        for (var i = 0; i < files.length; i++) {
            var f = files[i];

            // Only process image files.
            if (!f.type.match('image.*')) {
                continue;
            }

            var reader = new FileReader();
            reader.onload = onLoad;
            reader.readAsDataURL(f);
        }
    }

    document.getElementById('files').addEventListener('change', handleFileUpload, false);

    var image = localStorage.getItem('image');
    if (image !== null) {
        document.getElementById('image').src = image;
    }
</script>
0
On

Yeah absolutely, providing you have a cutting edge browser (Chrome or Firefox).

You want to use FileReader and readAsDataURL(). Take a look at the third example in this tutorial:

http://www.html5rocks.com/en/tutorials/file/dndfiles/