A guide on how to download files from API in Angular.
There is a specific use case when the service API request sends back a file as BLOB and we need to have the file downloaded in the user system through the browser (and not directly writing the file into the user system).
The code changes are pretty basic but figuring out these things for the first time might get confusing (it at least was in my case!) and hence, this article.
Prerequisites
I have referred to a custom method serviceWrapper() that I use in my Angular applications. For an insight on how I work with APIs, you can refer to this article —
Optimized Service/ API Integration for Angular
TL; DR
- Use file-saver for saving the incoming BLOB as a file.
- Set responseType as “blob” for the HTTP request.
Preparing file-saver package
We will use the following commands to install the package along with the type definitions —
npm install file-saver --save
npm install @types/file-saver --save-dev
Calling the API with responseType and file-saver
We will use the saveAs() method in file-saver package to save the incoming BLOB as a file. However, to receive the file as a BLOB, the responseType needs to be set as well.
Next Steps
You can refer to my Git repo for all the code. The working example in the sample application can be accessed from the “File Download” page —