Skip to content

Instantly share code, notes, and snippets.

@MartijnR
Last active November 17, 2015 17:54
Show Gist options
  • Save MartijnR/07e187574ccab1068527 to your computer and use it in GitHub Desktop.
Save MartijnR/07e187574ccab1068527 to your computer and use it in GitHub Desktop.
Demonstrates issue with Chrome retrieving and displaying blobs from indexedDB
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<ol>
<li>Image preview is shown to verify that blob is succesfully saved in indexedDB and can be retrieved</li>
<li>Refresh page, confirm image preview is still shown</li>
<li>Load or refresh page a few hours, or a day, later: Image can still be retrieved from store, is blob, has file size, but cannot be shown any more (404). See console.</li>
</ol>
Loaded from storage
<img id="image"/>
<script>
var db;
var request = indexedDB.open("demo2", 1);
function getImage(){
var url = "./nuthatch.png";
var xhr = new XMLHttpRequest();
console.log('Going to load image from ', url);
return new Promise(function(resolve, reject){
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if ( this.readyState === 4 ) {
if ( this.status >= 200 && this.status < 300 ) {
console.log('blob received', this.response);
resolve( this.response);
}
}
};
xhr.send();
});
}
function storeImage(blob) {
console.log("Storing image in IndexedDB");
var transaction = db.transaction(["images"], "readwrite");
var put = transaction.objectStore("images").put(blob, "image");
put.onsuccess = function(){
retrieveImage();
};
};
function retrieveImage(){
var transaction = db.transaction(["images"], "readonly");
return new Promise(function(resolve, reject){
transaction.objectStore("images").get("image").onsuccess = function (event) {
var imgFile = event.target.result;
var img = document.getElementById("image");
var imgUrl;
if (imgFile){
console.log("Retrieved image from indexedDB", imgFile);
imgURL = URL.createObjectURL(imgFile);
img.setAttribute("src", imgURL);
resolve(true);
} else {
console.log("image not found");
resolve(false);
}
};
});
}
request.onerror = function (event) {
console.error("Error creating/accessing IndexedDB database");
};
request.onsuccess = function (event) {
console.log("Success creating/accessing IndexedDB database");
db = event.target.result;
db.onerror = function (event) {
console.error("Error creating/accessing IndexedDB database");
};
retrieveImage()
.then(function(found){
if (!found){
getImage()
.then(storeImage);
}
});
}
request.onupgradeneeded = function(event) {
console.log("Creating object store");
db = event.target.result;
db.createObjectStore("images");
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment