How to upload images by saving to local storage with unique names?

Viewed 296

I'm a complete beginner and just started teaching myself code a couple days ago, so if this is not the right way to do it, feel free to let me know how you would do it instead.

I am trying to upload multiple images onto a webpage using javascript. So far, I have been able to save the data URL to local storage, but every time I select a new file, the saved URL get overwritten. Then, when I click "Choose File," all of the images become the same. Is there a way to save the data URL with unique names without having to change it in javascript every time?

HTML:

<!DOCTYPE html>
<html>
<head>
  <title>||Working with elements||</title>
</head>
<body>
  <div id="div1">The text above has been created dynamically.</div>

  <div>
      <label for="name"></label>
      <input type="file" id="name">
    </div>

</body>

<script src="test.js">
    </script>
</html>

JS:

window.addEventListener('load', function() {
        document.querySelector('input[type="file"]').addEventListener('change', function() {
            if(this.files && this.files[0]) {
                const x = document.querySelector('img'); 
                 x.src = URL.createObjectURL(this.files[0]);
            }
        });
    });


document.querySelector("#name").addEventListener("change", function() {
    const reader = new FileReader();

    reader.addEventListener("load", () => {
        sessionStorage.setItem("recent-image", reader.result);
    });

    reader.readAsDataURL(this.files[0]);
});

document.body.onclick = addElement;

function addElement () { 
  // create a new div element 
  const newDiv = document.createElement('img'); 
  const nameInput = document.querySelector('#name');
  

document.addEventListener("click", () => {
    const recentImageDataURL = sessionStorage.getItem("recent-image");
    if (recentImageDataURL) {
        newDiv.setAttribute("src", recentImageDataURL);
    }
});


  const currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 
}
1 Answers

The key of your session-store-entry is always the same: recent-image.

You need to use a different, unique key for each image. Then you need a way to choose which of these keys you want to show.

(Alternatively you could store a list or collection with all the images, instead of only one image per key.)

There are many different ways to create a unique key, because there are many different ways to define what unique means. There is lots of information about creating unique keys, but the topic is more complex than one might think. Be prepared to read a lot, or just choose a simple way that is good enough for now. E.g.

  • use a counter
  • use the current date-time in milliseconds
  • use a random number
  • a combination of the above

A simple solution would be like this:

    let recentImageId = '';

    // ...

    //-- a very simple 'unique key' function
    const getUniqueImageId = function(){
        return 'image_' + Date.now();
    }

    // ...

    recentImageId = getUniqueImageId();
    sessionStorage.setItem(recentImageId, reader.result);

    // ...

    const recentImageDataURL = sessionStorage.getItem(recentImageId);

Related