Storing Image to client-side using window local storage

window Jun 29, 2019

The LocalStorage API gives front-end web engineers access to a straightforward key-esteem datastore that can be utilized to spare information on a clients PC. Sparing information on the customer side can accelerate the presentation of your web applications as it can decrease the number of database questions that are required on the server. This opens up profitable server assets and can conceivably even lead to diminished foundation costs.

So how does storing image work on localstorage how to store them on client side,many users ask me this question so here is the solution and tuffest part which i have explain with the help of a simple project in which a user can upload many image, and save them on locastorage and the retrive image delete images.

So let's get started...

For first we need to create simple HTML file,

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Upload Image</title>
</head>
<body>
    
</body>
</html>

So first we need to upload image for that we need input:file for that i am using custom css.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Upload Image</title>
</head>
<body>
    <div class="row">
    <div class="input_box">
       
        <label for="">
            <input type="file" id="myFile" size="50" onchange="uploadImage(event)">
        </label>
    </div>
    </div>
</body>
</html>

I have created input box with onchange event with uploadImage(event) function  we will be using for uploading image.

Let's give it some css..

<style>
		.row{
        	display: flex;
        }
        .input_box {
            position: relative;
            height: 75px;
            width: 50%;
            margin: 0 auto;
            background-color: cadetblue;
            cursor: pointer;
            overflow: hidden;
            text-align: center;
            -webkit-transition: background-color ease-in-out 150ms;
            transition: background-color ease-in-out 150ms;
        }

        .input_box input {
            width: 100%;
            height: 100%;
            opacity: 0;
            overflow: hidden;
            position: absolute;
      
        }

        .input_box label {
            display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            -webkit-box-align: center;
            -ms-flex-align: center;
            align-items: center;
            width: 100%;
            height: 100%;
            font-weight: 400;
            text-overflow: ellipsis;
            white-space: nowrap;
            cursor: pointer;
            overflow: hidden;
        }

        .input_box label::after {
            content: '+';
            font-family: 'Material Icons';
            position: absolute;
            font-size: 2.5rem;
            color: #e6e6e6;
            top: calc(50% - 2.5rem);
            left: calc(50% - 1.25rem);
            z-index: 0;
            line-height: 2;
        }

        .input_box label:hover{
            background-color: transparent;
            color: cadetblue;
        }
</style>

So After that it will look something like this..

Now Lets Make Upload Function to upload Images to localstorage at client side.So let's get started ....

<script>
	function uploadImage(event)
    {
    	
    }
</script>

Now with the help of FileReader we will get the content of image file in the format for base64 and that content will be saved in localstorage with the name of file as key.

Now Local Storage have key and value attributes.In our case the file name will the key and content of image will be value.  

<script>
	  function uploadImage(event) {
            var reader = new FileReader();
            var name = event.target.files[0].name;
            reader.addEventListener("load", function () {
                if (this.result && localStorage) {
                    window.localStorage.setItem(name, this.result);
                } else {
                    alert();
                }
            });
            reader.readAsDataURL(event.target.files[0]);
        }
</script>

In the above first we making a new instance of file reader and after that we are storing the file name in name variable.

With the help of reader.readAsDataURL function we are getting the file content and with reader.addEventListener we are saving the image in localstorage.

If you see i have use two condition in above function i.e this.result && localstorage

this.result means the content which we get from reader and localstorage is to check is browser support localstorage or not.Some browsers do not support localstorage.

To save or to put content in localstorage we use localstorage.setItem() function in which we need to pass the key and value to save it.

Here is the output i have save one image to localstorage now let me save some more images to it and after that we are going to preview images from localstorage.

So now we can preview images for that we are going to use button show images on click of that we will use function showImage().Let's add the button with input inside row like ...

 <div class="row">
        <div class="input_box">

            <label for="">
                <input type="file" id="myFile" size="50" onchange="uploadImage(event)">
            </label>

        </div>

        <button onclick="showImages()" style="justify-content: center;" class="btn btn-primary">
            Show Images
        </button>
    </div>

add some css for it..

  .btn {
            padding: 16px 25px;
            border: 0;
            background-color: #444;
            color: white;
            border-radius: 50px;
            cursor: pointer;
            transition: .25s all;
            height: 50px;
            width: 30%;
            margin: 10px auto;
        }

        .btn:hover {
            transform: translateY(-2%);
            color: #444;
            background: transparent;
            border: 1px solid #444;
        }

        .btn:focus {
            outline: none;
        }

And the output will look something like this..

Now lets make the function showImage works.. for that we need to follow some steps so first we need to get images from the localstorage and for that we need to use localstorage.getItem() function.Now we want all images to display for that we are going to use window.localstorage.length and loop it until the length is less than localstorage length.

function showImages() {
	 for (let i = 0; i < window.localStorage.length; i++) {
   		let res = window.localStorage.getItem(window.localStorage.key(i));	
   }
}

Now in res we have save all the images now one by one we need to show them and for that we need Image Tag for that we need to make image tag using javascript using the new instance of  Image() function.

function showImages() {
	for (let i = 0; i < window.localStorage.length; i++) {
   		let res = window.localStorage.getItem(window.localStorage.key(i));
        var image = new Image();
        image.src = res;
   }
}

We have successfully make the image elements using javascript now we are going to append this body. For that we are going to use append(image) function and we are going to display image in div element so we need to make div with id preview in our body tag.

<div id="preview">

</div>

Now add css to make it look like row.

function showImages() {
	for (let i = 0; i < window.localStorage.length; i++) {
   		let res = window.localStorage.getItem(window.localStorage.key(i));
        var image = new Image();
        image.src = res;
        document.body.append(image);
   }
}

Now let's give some css to img tag

 img{
     height: 250px;
     border-radius: 10px;
     box-shadow: 0 0 1.2rem rgba(0,0,0,.25); 
     margin: 10px;
    }

Now the output will look something like this ...

But as much you click on the show Images button it will append the more image tag with same image so now we are going to check the if there is image tag in body the it will remove all image tag and then it will append the images.

function showImages() {
            var img = document.getElementById("img");

            var parentDiv = document.getElementById('preview');
            if (parentDiv.contains(img)) {
                parentDiv.prepend(img);
            } else if (parentDiv.contains(img) == false) {
                for (let i = 0; i < window.localStorage.length; i++) {
               let res = window.localStorage.getItem(window.localStorage.key(i));
                    var image = new Image();
                    image.src = res;
                    image.setAttribute('id', 'img');
                    parentDiv.append(image);
                }
            }

Now let's add something more interesting that is deleting image on button click.

So let's make delete button same as we make image but there is error that button is not constructor for that we are going to use createElement function.

and append with the image and onclick function we are going to call delete function which take image name as argument.

function showImages() {
            var img = document.getElementById("img");

            var parentDiv = document.getElementById('preview');
            if (parentDiv.contains(img)) {
                parentDiv.prepend(img);
            } else if (parentDiv.contains(img) == false) {
                for (let i = 0; i < window.localStorage.length; i++) {
               let res = window.localStorage.getItem(window.localStorage.key(i));
                    var image = new Image();
                     var button = document.createElement("button");
                    button.innerHTML = "Delete";
                    button.setAttribute('class' , 'deleteButton');
                    button.setAttribute('onclick',DeleteImage('${window.localStorage.key(i)}')`);
                    image.src = res;
                    image.setAttribute('id', 'img');
                    parentDiv.append(image);
                    parentDiv.append(button);
                }
            }

Now we can see the delete button with each image let's give css to deleteButton class

 .deleteButton{
            border: 0;
            background-color: rgb(236, 81, 81);
            color: white;
            border-radius: 50px;
            cursor: pointer;
            transition: .25s all;
            height: 50px;
            margin: 10px auto; 
        }

Now let's make the function DeleteImage().

function DeleteImage(name)
{
	window.localStorage.removeItem(name);
}

With the help of localstorage.removeItem we can delete the key and value pair.

So the output will look like ..

Now Let's delete the first image avatar.jpg

Avatar Image has been deleted.

That's it we done with uploading image to client side with the help of localstorage.

Thank You.

Abhishek

Hi There! I Am Abhishek Developer, Singer & Photographer. Living In Mumbai. My interests range from technology to entrepreneurship. I am also interested in food, designing, and education.