Hello friends, In this article, we will learn to upload file using file.io API in Angular 14.
Introduction:
- We upload the file using file.io API and create a link for file upload.
- Also, we can upload files and share the links via email, SMS, Slack, Discord, etc. Easy-to-use REST API.
Prerequisites:
- Basic Knowledge of Angular
- Visual Studio Code
First, create a new project in Angular using this command.
ng new angular-file-upload
Next, open the app.module.ts file and add the following code to this file.
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Next, open the app.component.ts file and add the following code to this file.
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 AppComponent { shortLink: string = ""; loading: boolean = false; file: File | any; baseApiUrl: string = "https://file.io"; constructor(private http: HttpClient) { } onChange(event: any) { this.file = event.target.files[0]; } onUpload() { this.loading = !this.loading; const formData = new FormData(); formData.append("file", this.file, this.file.name); this.http.post(this.baseApiUrl, formData).subscribe( (event: any) => { if (typeof (event) === 'object') { this.shortLink = event.link; this.loading = false; } }); } }
Next, open the app.component.html file and add the following code to this file.
<div class="d-flex justify-content-center pt-5"> <div class="row col-md-6"> <h3 class="text-center">Angular File Upload </h3> <div class="text-center"> <input class="form-control" type="file" (change)="onChange($event)"> <button (click)="onUpload()" class="btn btn-primary mt-2">Upload</button> </div> <div class="text-center jumbotron" *ngIf="shortLink"> <h2> Visit Here</h2> <a href="{{shortLink}}" target="_blank">{{shortLink}}</a> </div> <div class="text-center" *ngIf="loading"> <h3>Loading ...</h3> </div> </div> </div>
Now add this CDN to your main index.html.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
Output:
Summary
In this article, we learned how to upload a file and create links using file.io POST API.
Also, check How To Add Kanban Board In Angular 14