Upload folder and all its content in JavaScript

You can actually upload directories in all latest versions of Chrome, Firefox and Microsoft Edge. There are numerous working examples available to look at.

Here is a good, working example that I've previously used in a project

Quarklemotion Html5FileSelector

In addition, Dropzone JS also supports directory uploads as well and it works in Chrome, FF and Edge. I've just transitioned to using this in my own project.

Dropzone JS

These solutions recursively read the directory entries and list all of the files including their relative paths. If you want to rebuild the folder structure when uploading you will have to implement that using the relative paths and the appropriate algorithm.


It seems that Chrome and Firefox supports part of the filesystem API, but are not oficially supported.

This allows you to drop a folder and read all the content, here's the code i use on my app.

    function addFiles(e){
        e.stopPropagation();
        e.preventDefault();

        // if directory support is available
        if(e.dataTransfer && e.dataTransfer.items)
        {
            var items = e.dataTransfer.items;
            for (var i=0; i<items.length; i++) {
                var item = items[i].webkitGetAsEntry();

                if (item) {
                  addDirectory(item);
                }
            }
            return;
        }

        // Fallback
        var files = e.target.files || e.dataTransfer.files;
        if (!files.length)
        {
            alert('File type not accepted');
            return;
        }

        processFile(files);
    }

    function addDirectory(item) {
        var _this = this;
        if (item.isDirectory) {
            var directoryReader = item.createReader();
            directoryReader.readEntries(function(entries) {
            entries.forEach(function(entry) {
                    _this.addDirectory(entry);
                });
            });
        } else {
            item.file(function(file){
                processFile([file],0);
            });
        }
    },

Tags:

Javascript