Uploading the contents of a Folder

AYO AKINDOLANI
2 min readMay 6, 2019

--

Introduction

I had the opportunity to work on a project that will allow the user to upload the contents of a folder. I had to google up a lot of articles on how to upload directory contents and none really addressed what I intended to do. So this is what I did.

This is an Angular 7 and Electron project.

Before we go in deep discussion

In this post, you will learn how to upload the contents of a directory using JavaScript and the Node.js file system module.

Diving in…

Let’s create our input field and a button that allows us to browse through folders inside our html file.

<input type=”file” #folder style=”display: none” webkitdirectory (change)=”onFilesAdded(folder.files)” /><button class="file-upload-button" (click)="addFiles()"> Browse </button>

Now in our .ts file, import view child from angular/core

import { ViewChild} from '@angular/core';

Within our component class declaration, write the following:

export class ComponentName implements OnInit {
@ViewChild('folder') folder;
}

From our html file, when we click on the browse button, this method will be called

// click the browse button
addFiles() {
this.folder.nativeElement.click();
}

This will pop up a folder upload dialog window. Select desired folder and click ‘Ok’.

onFilesAdded(files) {
// get folder path
this.sourcePath = files[0].path;
// read all the files in the folder
const folderfiles = fs.readdirSync(folderdir);
for (let file of folderfiles) {
const filepath = path.join(this.sourcePath, file);
const contents = fs.readFileSync(filepath);
const f = new File([contents], file);
//do something with the file.
}
}

The method onFilesAdded() will be called , gets the folder path and read all the files in the folder.
For each of the files in the folder, get the relative path and read the contents.
Create a new instance of a File Object and we can do something with the file.

All of that put together should look like this:

component.html
component.ts

That’s it!

We made it all the way until the end! If you have any questions or feedback, let me know in the comments below. Thanks.

--

--

AYO AKINDOLANI
AYO AKINDOLANI

Written by AYO AKINDOLANI

Learn Code, Write Code, Teach Code | Software Engineer

No responses yet