javascriptoffline-storage

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


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?


Solution

  • 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>