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

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 )

<?php if (isset($_GET['LoadImg'])) {  header("Content-Type: image/png");  $file = file_get_contents($_GET['LoadImg']);  echo base64_encode($file);}?>

Read this may help you:

PS: maybe your Base64 is wrong?


Browsers have size limitations other than the localStorage limit of 5MB. The data for the <img src="data:image/jpeg;base64,..."> is also restricted and is usually much less than 5MB. The easiest way around this is to just pass the file-names via localStorage and let the browsers caching do the work.


Turns out, AJAX can't be used to reliably transfer binary data. The solution is to run the Base64 encoding server-side, and transfer the resulting string through AJAX.

The above php-code works. For whoever is looking for a ASP.Net / C# solution:

    public string Image(string relpath)    {        Response.ContentType = "image/jpeg";        string base64;        string filename = Request.PhysicalApplicationPath + relpath;        try        {            using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read))            {                var buffer = new byte[fs.Length];                fs.Read(buffer, 0, (int)fs.Length);                base64 = Convert.ToBase64String(buffer);            }        }        catch (IOException e)        {            return filename + " / " + e.Message;        }        return base64;    }

Please note that this code is NOT SECURE to expose directly to the outer world.I personally use a wrapper-function that parses the path from a db.