我有以下文件输入:
const file = document.getElementById('file'); file.addEventListener('change',e => { console.log(e.target.files[0]); });
<input id="file" type="file" />
解决方法
选择目录时,FileReader无法读取其内容,因此会产生错误.以下是如何为上载实现文件验证器的示例.
这个例子对所有现代浏览器都有完整的支持.
const input = document.querySelector('input') input.onchange = (e) => { const file = input.files[0] isThisAFile(file) .then(validFile => console.log('Woohoo! Got a File:',validFile)) .catch(error => console.log('Bummer,looks like a dir:',file,error)) } function isThisAFile(maybeFile) { return new Promise(function (resolve,reject) { if (maybeFile.type !== '') { return resolve(maybeFile) } const reader = new FileReader() reader.onloadend = () => { if (reader.error) { return reject(reader.error.name) } resolve(maybeFile) } reader.readAsBinaryString(maybeFile) }) }
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <Meta name="viewport" content="width=device-width,initial-scale=1.0"> <Meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input type="file" /> </body> </html>