javascript

Upload folder and all its content in JavaScript


How do I upload the content of a folder using JavaScript (client side)? The FileSystem API has not been adopted by browsers other than Chrome; I only get a File item with the name of the folder.

It should be possible, because Google Drive allows to drop a folder and all the content (folders and files) will be uploaded automatically.


Solution

  • 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);
                });
            }
        },