I have been attempting to write a program that processes files, and to do so I need to convert the array buffer of the file to a Uint8Array. The problem is when I run my code the array is empty. The array I am looking for is the fdata array. PLEASE DO NOT TELL ME TO USE A SERVER SIDE PROGRAM AS I AM UNABLE TO PUT SERVER SIDE CODE ON THE PLATFORM I AM USING.
<body>
<input type="file" id="files" name="files[]" multiple />
<div id="outimg"></div>
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
console.log(files);
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
console.log(e.target.result);
};
})(f);
reader.readAsArrayBuffer(f);
fdata = new Uint8Array(reader.result);
console.log(fdata);
window.cvd = [];
for (var i = 0, n = window.fdata.length; i < n; i += 3) {
var a = Array.from(window.fdata.slice(i, i + 3));
a.push(255);
window.cvd.push(a);
}
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
Reader result is available when the file is loaded so try to access it within the onload
event handler:
<body>
<input type="file" id="files" name="files[]" multiple />
<div id="outimg"></div>
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
console.log(files);
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
console.log(e.target.result);
fdata = new Uint8Array(reader.result);
console.log(fdata);
window.cvd = [];
for (var i = 0, n = window.fdata.length; i < n; i += 3) {
var a = Array.from(window.fdata.slice(i, i + 3));
a.push(255);
window.cvd.push(a);
}
};
})(f);
reader.readAsArrayBuffer(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>