文档
使用回调方式
<input type="file" />
<script>
let input = document.querySelector('input')
input.addEventListener('change', function (e) {
let file = e.target.files[0]
let reader = new FileReader()
reader.onload = (res) => {
console.log(res.target.result)
}
reader.readAsText(file)
})
</script>
改为异步方式
<input type="file" />
<script>
function readFile(file) {
return new Promise((resolve, reject) => {
let reader = new FileReader()
reader.onload = (res) => {
resolve(res.target.result)
}
reader.readAsText(file)
})
}
let input = document.querySelector('input')
input.addEventListener('change', function (e) {
let file = e.target.files[0]
readFile(file).then((res) => {
console.log(res)
})
})
</script>