How to save an image to localStorage using JavaScript

avatar
Borislav Hadzhiev

Last updated: Apr 4, 2024
4 min

banner

# Table of Contents

  1. How to save an image to localStorage using JavaScript
  2. How to save multiple images to localStorage using JavaScript

# How to save an image to localStorage using JavaScript

To save an image from an input type file to localStorage in JavScript:

  1. Use the FileReader() constructor to read the contents of the image.
  2. Save the result to localStorage.
  3. Optionally read the image from localStorage using the localStorage.getItem() method.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <input type="file" id="img-input" /> <br /> <br /> <img id="img-from-local-storage" /> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
const imageInput = document.getElementById('img-input'); imageInput.addEventListener('change', event => { // 👇️ Save the image to localStorage const image = event.target.files[0]; const reader = new FileReader(); reader.addEventListener('load', () => { localStorage.setItem('image', reader.result); }); if (image) { reader.readAsDataURL(image); } // 👇️ Take the image from localStorage // and display it const newImage = document.getElementById( 'img-from-local-storage', ); newImage.src = localStorage.getItem('image'); });

save image to local storage using javascript

The code for this article is available on GitHub

We accessed the image as event.target.files[0], however, you can also access the image directly on the input element.

index.js
const imageInput = document.getElementById('img-input'); imageInput.addEventListener('change', event => { const image = imageInput.files[0]; } )

We used the FileReader constructor to create a new FileReader object.

The FileReader object enables us to asynchronously read the contents of the image.

Note that the FileReader API can only access the contents of files that the user has explicitly selected, either by using an input field with a type of file or by using drag and drop.

index.js
reader.addEventListener('load', () => { localStorage.setItem('image', reader.result); });

The result property on the FileReader object returns the file's contents.

However, the property is only valid after the read operation is complete.

We used the readAsDataURL() method to read the contents of the File.

index.js
if (image) { reader.readAsDataURL(image); }
When the read operation is complete, the result property contains the data as a data: URL representing the file's data as a base64 encoded string.

We then used the document.getElementById() method to select an img element and then used the localStorage.getItem() method to set the src attribute of the image to the stored image.

The image is stored as a data URL (e.g. data:image/png;base64,...) in localStorage, so we can directly set the element's src attribute to the data URL string.

You can start a development server by saving the index.html and index.js files and running the following command.

shell
npx serve .

save image to local storage using javascript

When using this approach, note that there is a limit of 5MB for strings stored in localStorage.

# How to save multiple images to localStorage using JavaScript

The previous example only saved a single image to localStorage.

However, in some cases, you might have to save multiple images if your input type file has the multiple attribute set.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <h2>bobbyhadz.com</h2> <input type="file" id="img-input" multiple /> <br /> <br /> <img id="img-0" /> <img id="img-1" /> <script src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript.

index.js
const imageInput = document.getElementById('img-input'); imageInput.addEventListener('change', event => { const imageFiles = event.target.files; Array.from(imageFiles).forEach((image, index) => { const reader = new FileReader(); reader.addEventListener('load', () => { localStorage.setItem(`img-${index}`, reader.result); }); if (image) { reader.readAsDataURL(image); } }); const imageTags = document.querySelectorAll('#img-0, #img-1'); imageTags.forEach((img, index) => { img.src = localStorage.getItem(`img-${index}`); }); });

save multiple images to local storage

The code for this article is available on GitHub

We accessed the image files on the event.target property, however, you can also access them directly on the input element.

index.js
const imageInput = document.getElementById('img-input'); imageInput.addEventListener('change', event => { const imageFiles = imageInput.files; } )

We used the Array.from() method to convert the collection of files to an array to be able to use the Array.forEach() method.

index.js
Array.from(imageFiles).forEach((image, index) => { const reader = new FileReader(); reader.addEventListener('load', () => { localStorage.setItem(`img-${index}`, reader.result); }); if (image) { reader.readAsDataURL(image); } });

On each iteration, we create a new FileReader object, read the contents of the current image and save the data URL to localStorage.

You can optionally read the images from localStorage later and display them.

index.js
const imageTags = document.querySelectorAll('#img-0, #img-1'); imageTags.forEach((img, index) => { img.src = localStorage.getItem(`img-${index}`); });
The code for this article is available on GitHub

We used the document.querySelectorAll() method to select the 2 image elements on the page.

The last step is to set the src attribute of each image to the data URL that we get from the corresponding localStorage key.

I've also written an article on how to download images using JavaScript.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.