I am using the File API to upload a file and save its content as a variable in JavaScript. This is what I have so far but, the result that I get is undefined.
<body>
<input type="file" id="file" name="file" multiple />
<script>
function handleFileSelect(evt) {
// grab the file that was uploaded which is type File.
// evt is the event that was triggered
// evt.target returns the element that triggered the event
// evt.target.files[0] returns the file that was uploaded
var file = evt.target.files[0];
// instantiate a FileReader object to read/save the file that was uploaded
var reader = new FileReader();
// read the file and save as an array
fileArray = reader.readAsArrayBuffer(file);
window.alert("hello");
window.alert(fileArray);
}
document.getElementById('file').addEventListener('change', handleFileSelect, false);
</script>
FileReader
is asynchronous. you should set up onload
var reader = new FileReader();
reader.onload = function(){
console.log(reader.result);
};
// read the file and save as an array
reader.readAsArrayBuffer(file);