Angular for Enabling a File Upload and Hitting Post Api in Inputstream
Table of Contents
- Introduction
- Prerequisites
- Install Modules
- Project Setup
- Service Course
- Controller Course
- View File
- Register HttpModule/HttpClientModule
- Prerequisites
- Prerequisites
- Prerequisites
- Prerequisites
- Testing the APplication
- Source Lawmaking
Introduction
In this post I am going to bear witness you how to download file from server using Angular framework. Angular is a UI (user Interface) framework for building rapid application development. Here I volition utilise Angular 7/8/10/eleven/12/13 to download file from server side.
You lot tin can use any server side engineering and integrate this example with information technology for downloading file from server. I am going to utilise here Spring Boot framework equally a server side technology.
I volition provide link as well as button, on which user will click and download the file from server. I will too show how to give end users Save as option while downloading file and how to display file content on the browser.
Related Posts:
- Download file from server using React
Prerequisites
Angular 7/8/10/xi/12/13, Node v11.3.0/v12.9.i/v12.16.iii/v14.xv.5/16.12.0-16.13.0, npm half dozen.4.1/vi.x.2/half-dozen.14.4/vi.xiv.eleven/8.i.0-8.i.3
Spring Boot Residuum API to download File
Install Modules
Install the required module for Angular 7/eight/10/11/12/13: execute control npm install file-saver --save-dev (for 7/10)
or npm install @types/file-saver --save-dev (for eleven/12/13 version) in control line tool to install file-saver which is required for Save as choice.
Install the required module for Angular eight: execute control npm install @angular/http@latest in command line tool.
Go through the following steps for creating Angular project to download file from server using Athwart.
Project Setup
Become through the link Creating Angular Project to create a new project. Brand sure you give the project proper noun as athwart-file-download.
If you are asked to ostend Routing and default StyleSheet type, and then y'all can press y/CSS equally answers as shown in below paradigm:
For Angular 11, y'all will detect another selection to set whether you want to use stricter type or not. Hither I am using stricter type and later I will show you how to use stricter type for response and fault.
Now I will edit or add together the required files nether angular-file-download/src/app directory.
Remember the file extension ts (service.ts) indicates TypeScript, which is a file type.
Service Grade
Service is one of key blocks of every Angular application. Service is just a TypeScript class with or even without @Injectable decorator.
Once yous create the service class you demand to register it under app.module.ts file in providers array of @NgModule.
But here I won't annals in providers array of @NgModule, instead I volition use @Injectable({providedIn: 'root'}) to annals it for the whole application.
@Injectable is a decorator that has a property providedIn. root ways that you want to provide the service at the root level (AppModule).
When the service is provided at root level, Angular creates a single, shared instance of service and injects into any class that needs it. Registering the provider in the @Injectable metadata also allows Angular to optimize an application by removing the service if it is not used.
Create service file by executing the command ng g s <service proper noun>.
The beneath source code is written into file.service.ts file.
import {Injectable} from '@angular/cadre'; import {HttpResponse} from '@angular/mutual/http'; import {Http, ResponseContentType} from '@athwart/http'; import {Observable} from 'rxjs'; @Injectable({ providedIn: 'root' }) export grade FileService { constructor(private http: Http) {} downloadFile(): Appreciable<HttpResponse<Blob>>{ render this.http.get('http://localhost:8080/employees/download', { responseType: ResponseContentType.Blob }); } } For Athwart viii, change the downloadFile() office equally below:
downloadFile(): Observable<any>{ return this.http.get('http://localhost:8080/employees/download', {responseType: ResponseContentType.Blob}); } Update for Angular ten/eleven/12/xiii:
import {Injectable} from '@angular/core'; import {HttpClient, HttpResponse} from '@angular/common/http'; @Injectable({ providedIn: 'root' }) consign class FileService { constructor(private http: HttpClient) {} downloadFile(): whatever { return this.http.get('http://localhost:8080/employees/download', {responseType: 'hulk'}); } } In the above service form I am using HTTP Become method to get the file content from the URL http://localhost:8080/employees/download.
Update for Angular eleven/12/13:
If you are non using stricter type then your lawmaking should exist working fine every bit it is working for Angular ten. If y'all are using stricter type then y'all demand to brand changes to the post-obit lines in your src/app/app.component.ts file.
Beginning replace the line this.fileService.downloadFile().subscribe(response => { by the following line:
this.fileService.downloadFile().subscribe((response: any) => { 2d supplant the line }), error => console.log('Error downloading the file'), past the post-obit line:
}), (error: any) => panel.log('Error downloading the file'), That's it for Angular 11.
I am also accepting response as Blob (Binary Large Object). You may also specify any value from supporting values, such as, json, hulk, arraybuffer, text. Y'all can have a expect for more details on response type.
Controller Course
You demand controller class that handles request/response from clients or end users.
I will invoke the service class method in controller class for downloading file.
I accept used three means for downloading file – two ways for Save as functionality and ane style to show the file content on browser itself.
The below lawmaking is written in app.component.ts file.
Let's interruption up the lines within the download() function.
let blob:any = new Blob([response.hulk()], { type: 'text/json; charset=utf-8' }); The above line create a Blob object with file content in response and expecting the file of JSON blazon.
const url= window.URL.createObjectURL(blob); window.open up(url); The higher up two lines create a URL that will open the file in browser in new window. The above line shows the file content on browser, and then information technology does not requite you relieve every bit option.
fileSaver.saveAs(blob, 'employees.json'); The in a higher place line uses ready-fabricated FileSaver module that will open the file with Save as selection.
window.location.href = response.url The above line gives you Save as option but it may not work for Athwart xi.
import { Component } from '@athwart/core'; import { FileService } from './file.service'; import * equally fileSaver from 'file-saver'; import { HttpResponse } from '@angular/mutual/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { championship = 'Angular File Download'; constructor(private fileService: FileService) {} download() { this.fileService.downloadFile().subscribe(response => { //let blob:any = new Blob([response.blob()], { type: 'text/json; charset=utf-8' }); //const url= window.URL.createObjectURL(blob); //window.open(url); window.location.href = response.url; //fileSaver.saveAs(blob, 'employees.json'); }), error => console.log('Error downloading the file'), () => panel.info('File downloaded successfully'); } } Update for Athwart 10:
import { Component } from '@angular/core'; import { FileService } from './file.service'; import * as fileSaver from 'file-saver'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Athwart File Download'; constructor(private fileService: FileService) {} download() { this.fileService.downloadFile().subscribe(response => { let hulk:whatsoever = new Blob([response], { type: 'text/json; charset=utf-8' }); const url = window.URL.createObjectURL(blob); //window.open up(url); //window.location.href = response.url; fileSaver.saveAs(blob, 'employees.json'); }), fault => panel.log('Error downloading the file'), () => console.info('File downloaded successfully'); } } For Angular eleven and 12 with Stricter Blazon:
import { Component } from '@angular/cadre'; import { FileService } from './file.service'; import * as fileSaver from 'file-saver'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) consign form AppComponent { championship = 'Athwart File Download'; constructor(private fileService: FileService) {} download() { //this.fileService.downloadFile().subscribe(response => { this.fileService.downloadFile().subscribe((response: any) => { //when you lot employ stricter type checking let hulk:whatever = new Blob([response], { type: 'text/json; charset=utf-viii' }); const url = window.URL.createObjectURL(blob); //window.open up(url); //window.location.href = response.url; fileSaver.saveAs(blob, 'employees.json'); //}), error => console.log('Error downloading the file'), }), (error: whatsoever) => console.log('Error downloading the file'), //when you utilize stricter type checking () => console.info('File downloaded successfully'); } } For Angular 13:
You can utilise the post-obit code in Athwart 13:
import { Component } from '@athwart/cadre'; import { FileService } from './file.service'; import { saveAs } from 'file-saver'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export grade AppComponent { title = 'Angular File Download From Server'; constructor(individual fileService: FileService) {} download() { this.fileService.downloadFile().subscribe((response: any) => { let blob:any = new Hulk([response], { blazon: 'text/json; charset=utf-8' }); const url = window.URL.createObjectURL(blob); //window.open up(url); saveAs(blob, 'employees.json'); }), (error: whatever) => console.log('Fault downloading the file'), () => console.info('File downloaded successfully'); } } View File
I take created service class to fetch file data from a server URL but I need to provide a link or button for downloading the file.
In the view file I will give users two options for downloading the same file. I will apply link as well as button for downloading the same file from the server.
I call the download() function of controller class on click event.
The code is written into app.component.ts file.
<div style="text-marshal:eye"> <h1> Welcome to {{ title }} </h1> </div> <h2>Click below link to get employee data</h2> <div> <h3> Using Link <br/> <a href="#" (click)="download()">Download Employee Data</a> </h3> <h3>Using Button</h3> <input type="button" (click)="download()" value="Download Employee Data"/> </div> Registering HttpModule/HttpClientModule
In the service class I have used Http module which may not be found automatically. So I demand to register it in providers assortment of @NgModule.
And then brand sure y'all have the app.modules.ts file with the post-obit content.
In the beneath source, import {HttpModule} from '@angular/http'; and HttpModule inside imports: [ ] are included.
import { BrowserModule } from '@athwart/platform-browser'; import { NgModule } from '@angular/core'; import {HttpModule} from '@angular/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Update for Angular 10:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/mutual/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) consign grade AppModule { } Angular eleven/12/xiii:
Same every bit for Angular 10.
Plenty coding! Allow'southward test our awarding.
Testing the Application
Allow'southward presume that server side application is upwardly and running and the URL http://localhost:8080/employees/download is accessible.
Run the Angular application angular-file-download by executing command ng serve --open. Your application will open up at URL http://localhost:4200 in the browser and the page may look similar to the below image:
When you click on link or push button for downloading file you volition see below page with file salvage option:
When you employ the code for displaying data on browser inside download() function of controller code and click on button or link, so you should run into below output:
[{"id":1,"name":"Soumitra","email":"soumitra@email.com"},{"id":2,"name":"Liton","email":"liton@electronic mail.com"},{"id":three,"name":"Suman","email":"suman@email.com"},{"id":4,"name":"Debabrata","email":"debabrata@email.com"}] For server side code you tin read the post on Download file using Angular and Spring Boot.
Source Code
Download
Source: https://roytuts.com/download-file-from-server-using-angular/
0 Response to "Angular for Enabling a File Upload and Hitting Post Api in Inputstream"
Post a Comment