Skip to content

Instantly share code, notes, and snippets.

@gipi
Created July 17, 2012 14:41
Show Gist options
  • Save gipi/3129800 to your computer and use it in GitHub Desktop.
Save gipi/3129800 to your computer and use it in GitHub Desktop.
Use Javascript typed array to read raw data from a file (original code from http://www.html5rocks.com/en/tutorials/file/dndfiles/)
<!DOCTYPE html>
<html>
<head>
<title>POC</title>
<body>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
var raw = e.target.result;
// https://developer.mozilla.org/en/JavaScript_typed_arrays
var rawBytes = new Uint8Array(raw);
var hex = "";
for (var cycle = 0 ; cycle < raw.byteLength ; cycle++) {
hex += rawBytes[cycle].toString(16) + " ";
// TODO: more elegance
if (!((cycle + 1) % 8))
hex += "\n";
}
// Render thumbnail.
var span = document.createElement('pre');
span.innerHTML = hex;
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsArrayBuffer(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment