How to save and retrieve images from localStorage

Last updated: October 13, 2022.

You may think of localStorage as exclusively the domain of text data. After all, it is only possible to save string data there.

But, with a little help from the FileReader API, it is also possible to use it to store image files and retrieve them later on another page.

Local storage space is limited

In most browsers, total localStorage is limited to 5MB per website. It is therefore not a solution for saving very large images.

Converting an image to string format

Using JavaScript’s native FileReader, it is possible to read an image and output its content as a data URL.

A data URL is just like a regular URL except that it doesn’t point to an external resource. Instead, the image data is contained in data URL! (so they tend to be quite long).

Below is how you can read in a user-selected file using the FileReader. So you can see that its working, the data URL is set as the src of a new image element:

<input type="file" id="file-input-element">

<script>

const inputEl = document.getElementById('file-input-element');
// Gets input element

inputEl.addEventListener('change' , () => {
// Listens for new input file

    const file = inputEl.files[0]; 
    // Gets file from input element

    const fr = new FileReader();
    // Creates new FileReader object

    fr.readAsDataURL(file);
    // Set FileReader to output data as URL string

    fr.addEventListener('load', () => {
        // Waits for file reading to be complete

        const url = fr.result
        // Save result
        
        const img = new Image();
        img.src = url;
        document.body.appendChild(img);
        // Make URL src of image and append to DOM

    })

})

</script>

Now you have the image file expressed in string format, you are ready to save it to localStorage.

Saving and retrieving the image from localStorage

Now, that the image is expressed in string format, you can save it to localStorage in the normal way, using localStorage.setItem('key', value) syntax, where the data URL is passed in as the value.

inputEl.addEventListener('change' , () => {
    const file = inputEl.files[0]; 
    const fr = new FileReader();
    fr.readAsDataURL(file);

    fr.addEventListener('load', () => {
        const url = fr.result
        localStorage.setItem('image', url);
        // Saves image to localStorage
    })
});

Now, on another page, you can retrieve the data URL from localStorage and use it just like a regular URL:

const url = localStorage.getItem('image');
// Get data URL from localStorage

const img = new Image();
img.src = url;
document.body.appendChild(img);
// Set URL as src of image and append to DOM
Using sessionStorage

If you do not need to data to persist beyond the user's current session, you can use the exact same solution but using the sessionStorage rather than localStorage interfa.

Related links