1 7 Votes

HTML5: File Input with Folder Selection

Tutorial by Stefan Trost | 22/09/2016 at 11:40

In this tutorial, I would like to show you, how to implement an HTML 5 file input in which you can select an entire folder instead of some single individual files.

First, we want to have a look at the required HTML. We are using a normal input field with the type "file". In order to be able to select multiple files at once, we have added the attribute "multiple".

<input type="file" onchange="selectFolder(event);" webkitdirectory mozdirectory msdirectory odirectory directory multiple="multiple" />

For making a directory input out of the usual file input, additionally, we have specified the attributes webkitdirectory, mozdirectory, msdirectory, odirectory and directory. Actually, specifying only the attribute  "directory" should be enough at that point, but because we also want to support some older browsers, we have also added the browser specific attributes with the prefix webkit, moz, ms and od. If the browser is supporting one of those attributes, instead of the file dialog, now the directory dialog of the system is displayed.

Last, I also want to show you, how to work with the selected folder and how you are able to access the files of the folder. For this, we are using the following JavaScript, which will be automatically executed when changing the folder selection.

function selectFolder(e) {
   for (var i = 0; i < e.target.files.length; i++) {
      var s = e.target.files[i].name + '\n';
      s += e.target.files[i].size + ' Bytes\n';
      s += e.target.files[i].type;
      alert(s);
   }
}

We get all files located in the selected folder in the array e.target.files. In the code above, we are just looping through this array (the number of files is e.target.files.length) in order to show some information about the files such as name, size and type.

ReplyPositiveNegative

About the Author

Avatar AuthorYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile | Message

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.