Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if selected file is a directory or regular file?

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" />
You can Drag and Drop folder into this input. But how do I know if a user has dropped directory or a regular file?
like image 826
Oles Savluk Avatar asked Oct 05 '18 14:10

Oles Savluk


2 Answers

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>
like image 125
Iguatemi Garin Avatar answered Oct 26 '22 11:10

Iguatemi Garin


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).

like image 37
leximus Avatar answered Oct 26 '22 12:10

leximus