我正在使用文件 API 上传文件并将其内容保存为 JavaScript 中的变量。这是我到目前为止所得到的,但是我得到的结果是未定义。
<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
是异步的。你应该设置onload
var reader = new FileReader();
reader.onload = function(){
console.log(reader.result);
};
// read the file and save as an array
reader.readAsArrayBuffer(file);
关于javascript - 通过 JavaScript 查看上传的数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584893/