Angular 15 | NGX-Upload Single Multiple Image Uploader with Progress

In any modern web application, uploading files is an essential feature that needs to be implemented. Angular provides several libraries for file uploading, but ngx-upload is one of the most popular libraries that simplifies the file upload process by providing an easy-to-use API and UI components. Let’s say we are building a social media app…

By.

•

min read

In any modern web application, uploading files is an essential feature that needs to be implemented. Angular provides several libraries for file uploading, but ngx-upload is one of the most popular libraries that simplifies the file upload process by providing an easy-to-use API and UI components.

Let’s say we are building a social media app that allows users to upload images. We want to implement a file uploader that allows users to select and upload images to the server. We will use ngx-upload to implement this feature in our Angular application.

 

How to Add NGX-Upload in Angular App?

Step 1: Create a new Angular project using the Angular CLI by running the following command in your terminal:

ng new file-uploader

 

Step 2: Install ngx-upload and its dependencies using the following command:

npm install ngx-upload --save

 

Step 3: Import the NgxUploadModule in the AppModule:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgxUploadModule } from 'ngx-upload';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    NgxUploadModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

 

Step 4: Create a file upload component using the following command:

ng generate component file-upload

 

Step 5: Update the file-upload.component.html file to include the ngx-upload component:

<div class="container">
  <ngx-upload [url]="uploadUrl" [multiple]="false" (onUpload)="onUpload($event)">
    <button class="btn btn-primary btn-lg">Upload</button>
  </ngx-upload>
</div>

Here, we are using the ngx-upload component to display a file uploader UI. The [url] property specifies the upload URL, and the (onUpload) event is triggered when a file is uploaded. We also set the [multiple] property to false, which means that users can only upload one file at a time.

 

Step 6: Update the file-upload.component.ts file to handle the file upload event:

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

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html',
  styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent {
  uploadUrl = 'https://your-upload-url.com';

  onUpload(data): void {
    console.log(data);
  }
}

Here, we are handling the (onUpload) event and logging the response data to the console. We also set the [url] property to our server’s upload URL.

 

Step 7: Update the app.component.html file to include the file-upload component:

<div class="container">
  <app-file-upload></app-file-upload>
</div>

 

Step 8: Run the application using the following command:

ng serve

Open your browser and navigate to http://localhost:4200. You should see the file uploader UI. Click on the Upload button and select an image file to upload. You should see the uploaded file data logged to the console.

 

Some Common Issues with Fixes

 

Q1 How to set custom headers for file uploads in ngx-upload?

Solution: 

<ngx-upload
  [url]="uploadUrl"
  [headers]="{'Authorization': 'Bearer ' + authToken}"
  (onUpload)="onUpload($event)">
  <button class="btn btn-primary btn-lg">Upload</button>
</ngx-upload>

We have added a [headers] property to set the Authorization header with the authentication token.

 

Q2 How to limit the file size and type in ngx-upload?

Solution:

<ngx-upload
  [url]="uploadUrl"
  [maxFileSize]="1024 * 1024" // 1 MB
  [acceptedFileTypes]="['image/*']"
  (onUpload)="onUpload($event)">
  <button class="btn btn-primary btn-lg">Upload</button>
</ngx-upload>

We have added the [maxFileSize] property to limit the file size to 1 MB and the [acceptedFileTypes] property to allow only image files to be uploaded.

 

Q3 How to implement file drag and drop in ngx-upload?

Solution:

<ngx-upload
  [url]="uploadUrl"
  (onUpload)="onUpload($event)"
  [dropZone]="'drop-zone'">
  <div class="drop-zone">Drag and drop files here</div>
  <button class="btn btn-primary btn-lg">Upload</button>
</ngx-upload>

we have added the [dropZone] property to specify the ID of the drop zone element and added the drop zone element with the ‘drop-zone’ ID to the ngx-upload component.

 

Q4 How to show a progress bar while uploading files in ngx-upload?

Solution:

<ngx-upload
  [url]="uploadUrl"
  (onUpload)="onUpload($event)">
  <ng-template ngxUploadTemplate let-data="data">
    <div class="progress">
      <div
        class="progress-bar progress-bar-striped progress-bar-animated"
        role="progressbar"
        [style.width.%]="data.percentComplete">
        {{ data.percentComplete }}%
      </div>
    </div>
    <button class="btn btn-primary btn-lg" [disabled]="data.uploadInProgress">Upload</button>
  </ng-template>
</ngx-upload>

In the above code, we have used the ngxUploadTemplate directive to create a custom template for the ngx-upload component. We have added a progress bar element and bound its width to the percentComplete property of the data object passed to the onUpload event. We have also disabled the Upload button while the upload is in progress by binding the [disabled] property to the uploadInProgress property of the data object.

 

Q5 How to handle errors while uploading files in ngx-upload?

Solution:

<ngx-upload
  [url]="uploadUrl"
  (onUpload)="onUpload($event)"
  (onError)="onError($event)">
  <button class="btn btn-primary btn-lg">Upload</button>
</ngx-upload>

In the above code, we have added the (onError) event to handle errors during file uploads. We have defined the onError method in our component class to handle the error event.

onError(error): void {
  console.log('Error uploading file:', error);
}

In the onError method, we are logging the error to the console. We can also display an error message to the user or handle the error in any other way required by

 

Conclusion

In this tutorial, we have learned how to use ngx-upload to implement a file uploader in our Angular application. We created a new Angular project, installed ngx-upload, and added a file uploader component to our application. We also handled the file upload event and logged the response data to the console. With these steps, you can implement a file uploader in your Angular application using ngx-upload.

Leave a Reply

Your email address will not be published. Required fields are marked *