Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Official Blog
  • Nearby Places Finder
  • Direction Route Finder
  • Distance & Time Calculator
Menu

Angular 14 ngx-file-drop Example to Drag and Drop Multiple Files to Upload to Server in TypeScript

Posted on November 5, 2022

 

 

 

Welcome folks today in this blog post we will be uploading multiple files to server using drag and drop feature in browser using ngx-file-drop library in typescript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to initialize a new angular project using the below command as shown below

 

 

ng new angularapp

 

 

cd angularapp

 

 

Now we need to install the below libraries using the above command as shown below

 

 

npm i ngx-file-drop

 

 

After that you need to edit the app.module.ts file inside the angular project as shown below

 

 

app.module.ts

 

 

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
 
import { AppComponent } from './app.component';
import { NgxFileDropModule } from 'ngx-file-drop';
 
 
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    NgxFileDropModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

 

As you can see we are importing the NgxFileDropModule from the ngx-file-drop library at the very top of the file. And then we are importing the formsModule and HttpClientModule which are there from the base library of angular. And then we are adding the modules inside the imports array.

 

 

And now we need to add the html inside the angular template. So for this you need to edit the app.component.html file and copy paste the below code

 

 

app.component.html

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<div class="center">
    <ngx-file-drop dropZoneLabel="Drop files here" (onFileDrop)="dropped($event)"
    (onFileOver)="fileOver($event)" (onFileLeave)="fileLeave($event)">
        <ng-template ngx-file-drop-content-tmp let-openFileSelector="openFileSelector">
          Optional custom content that replaces the the entire default content.
          <button type="button" (click)="openFileSelector()">Browse Files</button>
        </ng-template>
    </ngx-file-drop>
    <div class="upload-table">
        <table class="table">
            <thead>
                <tr>
                    <th>Name</th>
                </tr>
            </thead>
            <tbody class="upload-name-style">
                <tr *ngFor="let item of files; let i=index">
                    <td><strong>{{ item.relativePath }}</strong></td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

 

 

As you can we have the upload files button where we have the section where the user can drag and drop files to upload it to the server. We can upload multiple files here using drag and drop. And then we are displaying the information of the uploaded file which is the actual path of the file. And here we are printing the relative path of the uploaded file. And here we are using the ngx file drop directive and then we are passing the options and also we are attaching the different events when the file is dropped inside the area or section what should happen we have attached all the events to this directive. And then we have the button to browse the files. Where a popup window will open where you can select the files to drag and drop to upload the files.

 

 

Drag and Drop File Upload

 

 

Now we will be enabling the drag and drop file upload for this we need to copy paste the below code inside the app.component.ts file and copy paste the below code

 

 

app.component.ts

 

 

TypeScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { Component } from '@angular/core';
import { NgxFileDropEntry, FileSystemFileEntry, FileSystemDirectoryEntry } from 'ngx-file-drop';
 
@Component({
  selector: 'demo-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
 
  public files: NgxFileDropEntry[] = [];
 
  public dropped(files: NgxFileDropEntry[]) {
    this.files = files;
    for (const droppedFile of files) {
 
      // Is it a file?
      if (droppedFile.fileEntry.isFile) {
        const fileEntry = droppedFile.fileEntry as FileSystemFileEntry;
        fileEntry.file((file: File) => {
 
          // Here you can access the real file
          console.log(droppedFile.relativePath, file);
 
          /**
          // You could upload it like this:
          const formData = new FormData()
          formData.append('logo', file, relativePath)
 
          // Headers
          const headers = new HttpHeaders({
            'security-token': 'mytoken'
          })
 
          this.http.post('https://mybackend.com/api/upload/sanitize-and-save-logo', formData, { headers: headers, responseType: 'blob' })
          .subscribe(data => {
            // Sanitized logo returned from backend
          })
          **/
 
        });
      } else {
        // It was a directory (empty directories are added, otherwise only files)
        const fileEntry = droppedFile.fileEntry as FileSystemDirectoryEntry;
        console.log(droppedFile.relativePath, fileEntry);
      }
    }
  }
 
  public fileOver(event){
    console.log(event);
  }
 
  public fileLeave(event){
    console.log(event);
  }
}

 

 

As you can see we have defined the different events for drag and drop where the file will be dropped and leaved out of the section. And then we are getting the location or relative path of the uploaded files. And also we are importing the required libraries from the ngx-file-drop library.

 

Now if you run the angular app by running the below command as shown below

 

 

ng serve

 

 

 

 

Recent Posts

  • Android Java Project to Crop,Scale & Rotate Images Selected From Gallery and Save it inside SD Card
  • Android Kotlin Project to Load Image From URL into ImageView Widget
  • Android Java Project to Make HTTP Call to JSONPlaceholder API and Display Data in RecyclerView Using GSON & Volley Library
  • Android Java Project to Download Youtube Video Thumbnail From URL & Save it inside SD Card
  • Android Java Project to Embed Google Maps & Add Markers Using Maps SDK
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • java
  • javascript
  • Koajs
  • kotlin
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • ReactNative
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme