How to save an image to localStorage and display it on the next page?

后端 未结 7 2080
逝去的感伤
逝去的感伤 2020-11-22 07:31

So, basically, I need to upload a single image, save it to localStorage, then display it on the next page.

Currently, I have my HTML file upload:

<         


        
相关标签:
7条回答
  • 2020-11-22 08:15
    document.getElementById('file').addEventListener('change', (e) => {
      const file = e.target.files[0];
      const reader = new FileReader();
      reader.onloadend = () => {
        // convert file to base64 String
        const base64String = reader.result.replace('data:', '').replace(/^.+,/, '');
        // store file
        localStorage.setItem('wallpaper', base64String);
        // display image
        document.body.style.background = `url(data:image/png;base64,${base64String})`;
      };
      reader.readAsDataURL(file);
    });
    

    Example CodePen

    0 讨论(0)
提交回复
热议问题