Last active
November 17, 2015 17:34
-
-
Save MartijnR/e0ccc45f28185ee6ecc9 to your computer and use it in GitHub Desktop.
Demonstrates issue with Chrome retrieving and displaying a File from indexedDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title></title> | |
</head> | |
<body> | |
<ol> | |
<li>Add image file to input</li> | |
<li>Confirm 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: File can still be retrieved from store, but now has file size 0. See console.</li> | |
</ol> | |
<input id="image-input" type="file" style="display:none;"/> | |
<img id="image"/> | |
<script> | |
var db; | |
var request = indexedDB.open("demo1", 1); | |
var input = document.getElementById("image-input"); | |
function storeImage(event) { | |
console.log("Storing image in IndexedDB"); | |
var blob = event.target.files[0]; | |
var transaction = db.transaction(["images"], "readwrite"); | |
var put = transaction.objectStore("images").put(blob, "image"); | |
put.onsuccess = function(){ | |
retrieveImage(); | |
input.setAttribute("style", "display: none;"); | |
}; | |
}; | |
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!", 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){ | |
input.removeAttribute("style"); | |
input.addEventListener("change", storeImage, false); | |
} | |
}); | |
} | |
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