How to check if selected file is a directory or regular file?
[EDIT] Added error name check. Thanks for the suggestions, @Cid and @DanielCuadra.
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' ||
reader.error.name === 'NotReadableError'
)) {
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>
the directory can be detected with "webkitGetAsEntry" method but it is not supported widely here is the reference
const file = document.getElementById('file');
file.addEventListener('change', e => {
console.log(e.target.files[0]);
});
file.addEventListener('drop',onDrop);
function onDrop(e) {
e.preventDefault();
e.stopPropagation();
var items = e.dataTransfer.items;
var files = e.dataTransfer.files;
var result = [];
for (var i = 0, item; item = items[i]; ++i) {
var entry = item.webkitGetAsEntry();
var obj = {
name: entry.name,
isDirectory: entry.isDirectory,
isFile: entry.isFile
}
result.push(obj);
}
console.log(result);
return result;
}
<input id="file" type="file" />
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).