Search code examples
angularfile-upload

Is it possible to select a folder and upload all the files inside it in angular 9?


I would like to upload all the files in a local folder without having to select each files one by one. Is it possible in angular 9?

Any help appreciated.


Solution

  • With webkitdirectory element you can easily get all the subfiles and subfolders of a selected folder.

    This is an HTMLInputElement so of course you can integrate it into an Angular app or in whatever that contain HTML.

    Here is an example of how to do it :

    In your HTML template

    <input type="file" (change)="onFolderSelected($event)" webkitdirectory multiple/>
    

    In your Component

    onFolderSelected(event){
        if (event.target.files.length > 0){
            let files = event.target.files;
        }     
    }
    

    Your files will contain all the subfiles that are in your folder and in the subfolders.

    If you only want to keep the files in the folder you specify and not in the subfolders you can iterate over all the files to check if they are or not in a subfolder like that.

    for (var i = 0; i < files.length; ++i) {
        if(!(files[i].webkitRelativePath.split('/').length > 2)){
            // Do whatever you want
        }
    }   
    

    Here I split the webkitRelativePath by / because this string contain the entire path from your folder to the file. So if the file is directly in the folder you selected, the path will be as folder/file. In case the file is in a subfolder, the path will be as folder/subfolder(s)/file so automatically there will be more than 2 elements in the array generated by the split function.