Our Expertise

Implementing File Upload with Angular Components

Sukrut Deo
Posted by Sukrut Deo on September 11, 2020

Angular is a widely popular framework that uses HTML and TypeScript to build single-page client applications. Angular is powerful, modern, and has a capable ecosystem that makes it a go-to platform for web, mobile, and desktop-native supports. Excellent User Interface and effective content management systems (CMS) are essential aspects of any application. File uploads contribute to maintain an effective CMS and hugely influence user productivity. To upload a file, you should know how to create file upload components. There are three crucial components that you should set up to upload files in Angular. I would also like to mention that creating file upload components is a little tricky. You have to deal with files that are in TypeScript, and you also need to write service. You can use the service to hold files of various sizes and collaborate with API to pass it.

In this blog, I will take you through sending a file to the back end in Angular. Before that, let’s go through the three components necessary to carry out the file upload in Angular:

1. FormData: With the help of FormData API, you can create a set of key/value elements. It lets you correspond to the form fields and the values as well. The Angular HttpClient allows you to send data to the server. Consider FormData instance equivalent to an HTML form that can be sent with the help of form-data encoding. Following is the example of how to create a FormData object:

const formData = new FormData();

2. HttpClientModule: It is a service module provided by Angular that allows you to perform the HTTP requests. You should import the HTTP module to use the HTTP service. This HTTPClientModule comprises APIs that provide front-end access to the server so that the data can be downloaded from or uploaded to the backend.

Let’s consider an example to see how the HttpClientModule works:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class FileHandlingComponent {
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get("url").
subscribe((data) ⇒ console.log(data))
}
}
3. Reactive forms: Reactive forms give you a model-driven approach that uses reactive programming. They are built around the streams, and the form fields in the form of streams have input values to access the data. Instead of depending on the streams, your templates can take advantage of the form state changes. Working with objects and models makes it easy to test Angular reactive forms. The forms give you the freedom to validate your form values, have multiple controls in your form group, and create adaptable forms.

 

You can import the module given below:

import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule
],
})
export class AppModule { }

Now that you have a clear idea of the three most essential components, let’s execute file upload in Angular:

  • Firstly, set up the HttpClientModule. As HttpClient is a separate Angular module, import it to your main application module before using it.
    import { AppComponent } from './app.component';
    import { HttpClientModule } from '@angular/common/http';
    @NgModule({
    declarations: [
    AppComponent,
    ],
    imports: [
    // other imports ...
    HttpClientModule
    ],
    providers: [],
    bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  • Create a UI component for file upload. In the HTML example below for the file selection, I have used the ‘formControlName’ to capture the file; then pass it to the onSubmitFile method to call the service to upload a file:
          
     
       
                
    
  • You should define the file upload method in the components. You can define instance of the formdata and then pass it to the injected service as shown below:
    onSubmitFile () {
    const formData = new FormData();
    formData.append('file', this.uploadFileReactiveFormObject.controls[fileData].value);
    this.fileUploadService.sendFileDocuments(formData).subscribe((event: any) => {
    if (typeof (event) === 'object') {
    // After file is shared successfully, we can perform next operations from here.
    console.log ('' file sharing is succesfully '');
    }
    });
    }
    
  • Lastly, you should create an Angular file upload service that can add the code for file uploading. The required import statements for creating service are mentioned below, to call the server post API use sendFileDocuments. This will send the formdata instance that contains the file object.
    import { HttpClient, HttpEvent, HttpErrorResponse, HttpEventType } from  '@angular/common/http';
    import { map } from 'rxjs/operators';
    @Injectable({
    providedIn: 'root'
    })
    export class fileUploadService {
    sendFileDocuments: string = "https://urlstring/";
    constructor(private httpClient: HttpClient) { }
    public sendFileDocuments(formData) {
    return this.httpClient.post(this.URL, formData);
    }
    }
    

Now the file has been sent to the server. The server API will give a response to the service to check whether the file has been uploaded successfully or not.

Executing file upload using Angular is reasonably simple if you know its components and how to use them. Now that you have a basic idea about them, what are you waiting for? Try this method and share your experience with us in the comments section. Happy coding!

Topics: Product & Test engineering, File Upload, Angular, Angular Components

Leave Comment

Subscribe Email

    Most Popular

    Post By Topic

    See all