How To Download ZIP File In Angular
In this article, we will learn how to download zip file in angular application.
So, let's start with the implementation
First, we need to create a new angular application using the following command in the terminal.
ng new angular-download-zip
Now, we need to install the jszip and file-saver npm package using the following command.
npm install jszip npm install file-saver
jszip : Using this javascript library can we created, read, and edited zip files.
file-saver : Using this javascript library we saved files on the client side.
Now, we need to add FormsModule into the app.module.ts file using the following code.
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Now, add the following code under the app.component.ts file.
import { Component } from '@angular/core'; import * as JSZip from 'jszip'; import * as FileSaver from 'file-saver'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title; uploadFiles; handleFileInput(files) { this.uploadFiles = files; } download() { var zip = new JSZip(); zip.file("Title.txt", this.title); var imgFolder = zip.folder("images"); for (let i = 0; i < this.uploadFiles?.length; i++) { imgFolder.file(this.uploadFiles[i].name, this.uploadFiles[i], { base64: true }); } zip.generateAsync({ type: "blob" }) .then(function (content) { FileSaver.saveAs(content, "Sample.zip"); }); } }
Now, Add the following code under the app.component.html file.
<textarea [(ngModel)]='title' name="title" rows="5" cols="50"></textarea> <hr> <input type="file" (change)="handleFileInput($event.target.files)" multiple> <button (click)="download()">Download</button>
In the aforementioned example, a zip file called "Sample.zip" will be produced. with one "Title.txt" text file and a "images" folder that might contain user-uploaded images.
Now, run the application using the ng serve command into the terminal and see the browser screen we are able to browse file and download zip file.
Conclusion
In this article, we learned how to download zip file in angular application using the jszip and file-saver npm package.
I hope this article helps you and you will like it.👍
Please give your valuable feedback and comments or suggestion in the comment section
If you have any doubt or confusion then free to ask in the comment section.