从本地存储获取图像

时间:2019-05-25 17:13:17

标签: javascript local-storage

我有上传图片的输入。我将图像存储在浏览器的Loacal存储中。上传图像后,我在本地存储中获取了信息。使用此信息,我想在页面上显示图像。我创建了下一个脚本:

document.getElementById('register').onclick = function () {
        var userImg = document.getElementById('img_user').value;
        localStorage.setItem('Img', userImg);
    };
 <form action="">
  <input id="img_user" type="file">
  </form>
  <button id="register">Register Me</button>
要从本地存储获取有关图像的数据,我知道我应该使用localStorage.getItem('Img'),但是显示在本地存储中上传的图像应该使用什么?

1 个答案:

答案 0 :(得分:0)

您可以这样做,

<html>
<head></head>
<body>
<form action="">
  <input id="img_user" type="file">
  </form>
  <button id="register">Register Me</button>
  <img id="uploaded_img" />

  <script>
    function uploadImg(reloadElement) {
        var file = document.getElementById('img_user').files[0];
        if (file) {
            var name = file.name;
            var ext = name.substr(name.lastIndexOf(".") + 1, 4).toLowerCase()
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                var binaryString = e.target.result.toString();

                //upload the data(binaryString) and then onsuccess of call back you can set the image as below or store it on localstorage whatever u want

                if (reloadElement) {
                    document.getElementById(reloadElement).src = binaryString;
                }
            };
        }
    }



    document.getElementById('register').onclick = function () {
        uploadImg('uploaded_img');
    };
  </script>
</body>
</html>

您可以将binaryString数据上传到服务器端