Angular is a popular JavaScript framework used for building single-page applications. In some cases, you may need to download files from an API endpoint and save them on the client’s computer. In this tutorial, we’ll show you how to accomplish this in Angular with ease.
Downloading and Saving Files from an API
To download and save a file from an API in Angular, we’ll need to make an HTTP request to the API endpoint that returns the file. We’ll then use the file-saver
library to save the file on the client’s computer with a specified filename.
Here is a sample Angular code that you can use to achieve your desired functionality
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { saveAs } from 'file-saver';
@Injectable()
export class ApiService {
private apiUrl = 'https://your-api-url.com';
constructor(private http: HttpClient) {}
downloadFile(): void {
const headers = new HttpHeaders().set('Accept', 'application/vnd.ms-excel');
this.http.get(`${this.apiUrl}/your-endpoint`, { headers, responseType: 'blob' })
.subscribe(
(response: any) => {
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
const fileName = contentDispositionHeader.split(';')[1].trim().split('=')[1];
saveAs(response.body, fileName);
},
(error: any) => {
console.error('Error: ', error);
// show error message to the user
}
);
}
}
In the above code, we are injecting the HttpClient module to make HTTP requests. In the downloadFile()
method, we set the headers to indicate that we want to download an Excel file. We then make an HTTP GET request to the API endpoint that returns a file. We set the responseType to ‘blob’ to tell Angular that the response is binary data.
If the request is successful, we extract the file name from the Content-Disposition header, create a new Blob
object with the response body, and use the saveAs()
method from the file-saver
library to save the file on the client’s computer.
If there is an error, we simply log the error to the console and show an error message to the user.
The saveAs()
method is not a built-in method in Angular or JavaScript. It is a method provided by the file-saver
library that allows us to save a Blob or File object to the user’s computer with a specified filename.
Here’s a simple implementation of the saveAs()
method:
function saveAs(blob: Blob, fileName: string) {
const link = document.createElement('a');
link.download = fileName;
link.href = window.URL.createObjectURL(blob);
link.click();
window.URL.revokeObjectURL(link.href);
}
In the above code, we create a new anchor element (<a>
) and set its download attribute to the desired filename. We then create a URL object with the createObjectURL()
method and set the href
attribute of the anchor element to the URL.
We then programmatically click the anchor element to trigger the file download. Finally, we revoke the URL object with the revokeObjectURL()
method to free up memory.
Note that the saveAs()
method may not work on older browsers or certain mobile devices. In those cases, you may need to provide an alternative way for users to download the file.
Example 2
Downloading and Saving Files from an API
To download and save a file from an API in Angular, we’ll need to make an HTTP request to the API endpoint that returns the file. We’ll then use the file-saver
library to save the file on the client’s computer with a specified filename.
Here’s a step-by-step guide to accomplish this:
Step 1: Install Dependencies
First, we’ll need to install the file-saver
library and its typings:
npm install file-saver @types/file-saver --save
Step 2: Create a Service to Handle the API Request
Next, we’ll create a service that handles the API request to download the file. We’ll inject the HttpClient
module to make the HTTP request and use the saveAs()
method from the file-saver
library to save the file.
Here’s an example of what the service might look like:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { saveAs } from 'file-saver';
@Injectable({
providedIn: 'root'
})
export class FileService {
constructor(private http: HttpClient) {}
downloadFile(url: string, fileName: string): void {
const headers = new HttpHeaders().set('Accept', 'application/octet-stream');
this.http.get(url, { headers, responseType: 'blob' }).subscribe(
(response: any) => {
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
const regex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
const matches = regex.exec(contentDispositionHeader);
const sanitizedFileName = matches[1].replace(/['"]/g, '');
const file = new Blob([response.body], { type: response.type });
saveAs(file, sanitizedFileName);
},
(error: any) => {
console.error('Failed to download file', error);
}
);
}
}
In the above code, we have a downloadFile()
method that takes the API endpoint URL and the desired filename as parameters. We set the Accept
header to application/octet-stream
to indicate that we want to download a binary file.
If the request is successful, we extract the filename from the Content-Disposition
header using a regular expression. We then create a new Blob
object with the response body and use the saveAs()
method from the file-saver
library to save the file on the client’s computer with the specified filename.
If there is an error, we simply log the error to the console.
Step 3: Call the Service Method from a Component
Finally, we can call the downloadFile()
method from a component when the user wants to download the file. Here’s an example of how to do this:
import { Component } from '@angular/core';
import { FileService } from './file.service';
@Component({
selector: 'app-file-downloader',
templateUrl: './file-downloader.component.html'
})
export class FileDownloaderComponent {
constructor(private fileService: FileService) {}
downloadFile(): void {
const url = 'http://example.com/api/download';
const fileName = 'example.xlsx';
this.fileService.downloadFile(url, fileName);
}
}
In the above code, we have a FileDownloaderComponent
that injects the FileService
we created earlier. We have a downloadFile()
method that calls the downloadFile()
method on the FileService
with the API endpoint URL and the desired filename.
When the user clicks a button or performs an action that triggers the downloadFile()
method, the file will be downloaded from the API and saved on the client’s computer with the specified filename.
Application Source Code @ LearnSmartCoding GitHub
Check out other topics that might interest you.
- Automating API Requests with C# and Azure Functions using HttpTrigger
- How to Create a Custom Autocomplete Component in Angular | Step-by-Step Guide
- Using Local Storage in Angular Applications: A Practical Guide with Real-Life Examples
- How to Implement reCAPTCHA in an Angular Application: A Step-by-Step Guide
- How to Show a Warning Message to Users When They Try to Close Your Website
- Lazy Loading in Angular: Boosting Performance and User Experience
- Understanding the CanLoad Guard in Angular: Real-time Example
- How to Use Multiple Angular AuthGuards in canActivate | Step-by-Step Guide
- Angular Custom Directives: A Beginner’s Guide with Real-Time Scenario
Conclusion
In this tutorial, we learned how to download and save files from an API in Angular using the file-saver
library. We created a service that handles the API request and saves the file using the saveAs()
method, and we called this service method from a component to trigger the download.
By following these steps, you can easily download and save files from an API in your Angular applications.