The most integral part of JavaScript projects that developers carry out is uploading files. Whenever you want to create a file upload angular, ensure you thoroughly go through the needs of your project.
You can use Angular components like Reactive forms to create a file upload module in Angular. FormData and HTTPClient Module.
Many developers find it hard to create file upload Angular components because of files in JavaScript and API.
Learning what these components entail and applying them will make it easy for developers to create file upload Angular.
What is Angular?
Developers use Angular as a growth platform and structure to make single-page applications available in JavaScript or TypeScript.
Although Angular’s structure is written in TypeScript, you can import it onto your project by enabling it through libraries.
Angular’s framework depends on NgModules, an accumulation of segments arranged into valuable sets. These modules allow you to characterize your applications and coordinate different segments created with Angular.
Each time you create an application in Angular, it possesses a root module.
This module allows you to use bootstrapping and select several feature modules you want. Inside every module are segments that characterize the perspectives accessible for use in your application.
These perspectives are sets of screen components that you can use codes to check.
How to Create a File Upload Module in Angular?
You can use three modules to create your file upload in Angular.
Methods
FormData
FormData API helps you create a bunch of key or value components. It allows you to relate to the structure fields and qualities.
The Angular HttpClient allows you to send information to the server. You can consider the FormData case identical to an HTML structure that you can send with the assistance of FormData encoding.
You can create a FormData object with the following code:
const formData = new FormData();
HttpClient Module
HttpClient module by Angular enables you to execute requests by HTTP. You must import the HTTP module if you want to use the HTTP service.
The HTTPClient module contains APIs that give front-end admittance to the server so they can download data and transfer it to the back-end. The following codes show the process of how to import HttpClient module with app.module.ts:
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))
}
}
Reactive Forms
Reactive forms allow you to confirm values and create forms for adjusting effective controls and several controls in a group. Using reactive forms gives a developer an ideal-driven suggestion that uses responsive programming.
Through reactive forms, you can handle form inputs with values that alternate. When working with models and objects, it is simple to test reactive forms for AngularJS upload files. Just like the HttpClient module, you can import reactive forms with app.module.ts with the following codes:
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports …
ReactiveFormsModule
],
})
export class AppModule { }
Step-by-Step
Having learned how to create a file upload module in Angular through three methods, we will discuss how to create an upload file in the following section.
1. Using all three components at once
First, you need to import the components through the app.module.ts with the following codes:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule, // required for input file change detection
ReactiveFormsModule,
HttpClientModule, // this is required for the actual http request
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
After that, create an upload button and alter the event with app.component.html with the following codes:
<div class="container">
<div class="row mt-5">
<div class="col-md-4">
<div class="mb-3">
<label for="formFile" class="form-label">Upload file example</label>
<input (change)="this.onFilechange($event)" class="form-control" type="file" id="formFile">
<button (click)="this.upload()" type="button" class="btn btn-primary mt-3">Upload</button>
</div>
</div>
</div>
</div>
Next, create a service that will ensure your upload process with the following codes with app.component.ts:
import { UploadService } from './upload.service';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
file: File = null;
constructor(
private uploadService: UploadService
){
}
onFilechange(event: any) {
console.log(event.target.files[0])
this.file = event.target.files[0]
}
upload() {
if (this.file) {
this.uploadService.uploadfile(this.file).subscribe(resp => {
alert("Uploaded")
})
} else {
alert("Please select a file first")
}
}
}
Finally, make a post request through upload.service.ts with the following codes:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UploadService {
constructor(
private httpClient: HttpClient,
) { }
public uploadfile(file: File) {
let formParams = new FormData();
formParams.append('file', file)
return this.httpClient.post('http://localhost:3000/uploadFile', formParams)
}
}
You can also visit Github to import these codes.
2. Using two components
Another method you can apply is using two components, FormData and HttpClient module.
The next thing to do is import the HttpClient module into your application module:
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 user interface segment for your Angular material file upload with the following code:
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { UploadComponent } from './upload.component'
import {
MatButtonModule,
MatDialogModule,
MatListModule,
MatProgressBarModule,
} from '@angular/material'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { FlexLayoutModule } from '@angular/flex-layout'
import { HttpClientModule } from '@angular/common/http'
@NgModule({
imports: [
CommonModule,
MatButtonModule,
MatDialogModule,
MatListModule,
FlexLayoutModule,
HttpClientModule,
BrowserAnimationsModule,
MatProgressBarModule,
],
declarations: [UploadComponent],
exports: [UploadComponent],
})
export class UploadModule {}
Define the file upload in the segments:
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 '');
}
});
}
Finally, create a service that aids AngularJS upload files for file uploading with the following codes:
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);
}
}
The result of the codes will show that the file upload is successful with the server receiving the file.