locked
How to keep image after refreshing my page? RRS feed

  • Question

  • User-2071692902 posted

    Hi

    According to the last replay in this post Click Here To see the Post

    I want after browsing for image and display it on page to keep it in the same page not in the next page as the last replay does.

    Thank you advance any help will be appreciated.

    Tuesday, February 26, 2019 10:01 PM

Answers

  • User839733648 posted

    Hi Omanxp45-1,

    I suggest that you could just add an if-statement to check if localStorage is null.

    Here is my testing code.

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script>
            window.onload = function () {
                if (localStorage.getItem("imgData") === null) {
                    var bannerImage = document.getElementById("bannerImg");
                    imgData = getBase64Image(bannerImage);
                    localStorage.setItem("imgData", imgData);
    
                }
                else {
                    var dataImage = localStorage.getItem('imgData');
                    bannerImg = document.getElementById('bannerImg');
                    bannerImg.src = dataImage;
                }
                document.getElementById("fileInput").onchange = function () {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        document.getElementById("bannerImg").src = e.target.result;
                        imgData = (e.target.result);
                        localStorage.setItem("imgData", imgData);
                    }
    
                    reader.readAsDataURL(this.files[0]);
    
                }
    
            }
            function getBase64Image(img) {
                //save the image as a Base64.
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
    
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);
    
                var dataURL = canvas.toDataURL("image/png");
    
                return dataURL;
            }
        </script>
    </head>
    <body>
        <img src=" " id="bannerImg" />
        <input id="fileInput" type="file" />
    </body>
    </html>

    result:

    Best Regards,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, February 27, 2019 3:30 AM