Forked from robnyman/arraybuffer-blob-filereader-localStorage.js
Created
July 14, 2012 09:54
-
-
Save lemonhall/3110306 to your computer and use it in GitHub Desktop.
Get file as an arraybuffer, create blob, read through FileReader and save in localStorage
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
// Getting a file through XMLHttpRequest as an arraybuffer and creating a Blob | |
var rhinoStorage = localStorage.getItem("rhino"), | |
rhino = document.getElementById("rhino"); | |
if (rhinoStorage) { | |
// Reuse existing Data URL from localStorage | |
rhino.setAttribute("src", rhinoStorage); | |
} | |
else { | |
// Create XHR, BlobBuilder and FileReader objects | |
var xhr = new XMLHttpRequest(), | |
blobBuilder = new (window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.OBlobBuilder || window.msBlobBuilder), | |
blob, | |
fileReader = new FileReader(); | |
xhr.open("GET", "rhino.png", true); | |
// Set the responseType to arraybuffer. "blob" is an option too, rendering BlobBuilder unnecessary, but the support for "blob" is not widespread enough yet | |
xhr.responseType = "arraybuffer"; | |
xhr.addEventListener("load", function () { | |
if (xhr.status === 200) { | |
// Append the response to the BlobBuilder | |
blobBuilder.append(xhr.response); | |
// Create a blob with the desired MIME type | |
blob = blobBuilder.getBlob("image/png"); | |
// onload needed since Google Chrome doesn't support addEventListener for FileReader | |
fileReader.onload = function (evt) { | |
// Read out file contents as a Data URL | |
var result = evt.target.result; | |
// Set image src to Data URL | |
rhino.setAttribute("src", result); | |
// Store Data URL in localStorage | |
try { | |
localStorage.setItem("rhino", result); | |
} | |
catch (e) { | |
console.log("Storage failed: " + e); | |
} | |
}; | |
// Load blob as Data URL | |
fileReader.readAsDataURL(blob); | |
} | |
}, false); | |
// Send XHR | |
xhr.send(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment