【发布时间】:2016-01-06 00:33:43
【问题描述】:
我正在通过JavaScript 读取一个数组,并将该数组的大小保存在 reader.onload 事件中。我认为文件上传完成后会调用reader.onload 函数。
event.target.result 存储该数组。我希望将该数组保存为变量以在其他函数中使用,但是我尝试初始化一个空数组并使用
slice
功能,但是,它没有工作。控制台返回一个未定义的值。
这里是代码
<!DOCTYPE html>
<html>
<head>
<title> Home Page </title>
</head>
<body>
<input type="file" id="file" name="files[]" multiple/>
<output id="list"></output>
<p id="demo"></p>
<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, type File
var file = evt.target.files[0];
var myArray = [];
// instantiate a FileReader object to read/save the file that was uploaded
var reader = new FileReader();
// when the load event is fired (the file has finished uploading) this function is called
reader.onload = function(event) {
// the result attribute contains an ArrayBuffer representing the file's data.
var arrayBuffer = event.target.result;
myArray = arrayBuffer.slice(0);
document.getElementById("demo").innerHTML = arrayBuffer.byteLength;
}
// read the file and save as an array. Once the read is finished loadend is triggered
reader.readAsArrayBuffer(file);
console.log(myArray.byteLength);
}
//console.log(myArray.byteLength);
document.getElementById('file').addEventListener('change', handleFileSelect, false);
</script>
</body>
【问题讨论】:
标签: javascript jquery html fileapi