I have the following file input:
const file = document.getElementById('file');
file.addEventListener('change', e => {
console.log(e.target.files[0]);
});
<input id="file" type="file" />
When a directory is selected, the FileReader can't read its content, so an error is produced. Here is an example of how you could implement a File Validator for the uploads.
This example has full suport on all modern browsers.
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 && reader.error.name === 'NotFoundError') {
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>
You should provide additional attributes to your input tag
<input id="file" type="file" webkitdirectory directory multiple />
then change event would provide you info about all files inside your folder with file path inside file object (but not about folder itself).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With