Retrieve an image from the server, store it in localStorage, and display it

后端 未结 4 633
终归单人心
终归单人心 2021-02-01 10:12

This should be simple enough, but after wrestling with it for hours, I still can\'t get it to work. So far, all my attempts have resulted in the image becoming \'corrupted or tr

4条回答
  •  伪装坚强ぢ
    2021-02-01 10:48

    • DEMO: http://so.lucafilosofi.com/retrieve-an-image-from-the-server-store-it-in-localstorage-and-display-it

    Javascript (AJAX call)

    function LoadImg(filename) {
        var xmlhttp;
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {     
                document.getElementById("documentHolder").src = "data:image/png;base64," + xmlhttp.responseText;
            }
        };    
        xmlhttp.open("GET", 'load.php?LoadImg='+filename );
        xmlhttp.send(null);
    }
    

    PHP ( load.php )

    
    

    Read this may help you:

    • Base 64 encode vs loading an image file
    • How to encode image data within an HTML file?
    • How can you encode a string to Base64 in JavaScript?
    • Get image data in JavaScript?

    PS: maybe your Base64 is wrong?

提交回复
热议问题