Reputation: 668
I try to stock an image in the localStorage using an Ajax request.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript">
window.onload = function() {
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) {
var storedImage;
if (localStorage.getItem('imgtest')) {
storedImage = localStorage.getItem('imgtest');
alert("get");
}
else {
storedImage = xmlhttp.responseText;
localStorage.setItem('imgtest',storedImage);
alert("set");
}
document.getElementById("test").style.backgroundImage = 'data:image/png;base64,' + storedImage;
}
}
xmlhttp.open("GET","img.png");
xmlhttp.setRequestHeader("Content-type","image/png");
xmlhttp.send();
}
</script>
</head>
<body>
<div id="test" style="width: 100px; height: 100px;"></div>
</body>
</html>
I can store the stream, but the image is not displayed.
Maybe it is because of my encoding, I don't know. Can you tell me what I do wrong or if there is a better way to do this ?
Upvotes: 4
Views: 493
Reputation: 88
Did you try with url() like this:
document.getElementById("test").style.backgroundImage = 'url(data:image/png;base64,' + storedImage + ')';
Upvotes: 2