Skip to main content

Download a file with Angular2+ and FileSaver.js

Why should your Angular code download a file?

Of course your webserver can deliver files and you can just add a simple link to your website but what if the file is delivered by a webservice and the webservice requests authentication (i.e. OAuth) to protect the file from unauthorized access?
In this case you might have the requirement to download the file in your code and then tell the browser to save it to the hard disk.

How to do that? 
First of all you need to add filesaver.js to your project. 

npm install file-saver --save

..and add the typings

npm install @types/file-saver --save-dev

More information about filesaver you can find on the filesaver github pages.

To download the file via http you need to implement a service. The following imports are required:

import { Injectable } from '@angular/core';
import { HttpResponseRequestOptionsResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx'

Http of course is required to load data from remote. Response is what is delivered by the http request and you have to get the data from the response. Before that you have to add request options to the call and tell the response content type. You will read more about that in a few moments.
Here is the code of the service:

@Injectable()
export class DownloadService {

  constructor(private httpHttp) { }

  public getFile(pathstring):Observable<Blob>{
      let options = new RequestOptions({responseType: ResponseContentType.Blob});
      
      return this.http.get(pathoptions)
              .map((responseResponse=> <Blob>response.blob())              
              .catch(this.handleError);
  }


Let's explain what is happening here.
public getFile(pathstring):Observable<Blob>

The function returns data of the type Blob which is a container for unchanged raw data. Yes, this is the data you want the browser to save as a file.
To get a Blob you have to tell which response content type you are expecting.
let options = new RequestOptions({responseType: ResponseContentType.Blob});

The request options have to be handed over to the get request.
this.http.get(pathoptions)

If you do not tell the browser the response content type you will see an error message like'The request body isn't either a blob or an array buffer'
The response has a function that can deliver the blob by calling response.blob(). 
Btw. if the file that you want to download from a webservice is protected by i.e. OAuth the options part of the code might look like this:
let headers = new Headers({'Authorization': this.getBearerToken()});
      let options = new RequestOptions({
          headers: headers
          responseType: ResponseContentType.Blob
        });

You just have to add the Authorization header including the token or whatever you use...


How to save the file?

Let's assume you have a component called DownloadComponent which provides a button to click to trigger the file download. In this component you need to import the filesaver.

import * as FileSaver from 'file-saver';

...and make your service visible.

constructor(private apiDownloadService)

Clicking the button calls the function downloadFile in your component.

(click)="downloadFile()"

This function calls the service which loads the data and delivers a Blob.

  downloadFile(){
    
    this.api.getFile("favicon.ico")
      .subscribe(fileData => FileSaver.saveAs(fileData"favicon.ico"));
  }

The function saveAs expects a Blob in the first parameter and the file name in the second parameter. For more information have a look at the filesaver.js documentation at https://github.com/eligrey/FileSaver.js.
FileSaver.saveAs(fileData"favicon.ico")

That's it. In the end the browser should show you that the file has been saved or depending on your browser settings ask you where to save to.


Comments

Popular posts from this blog

Typescript: json2ts is a nice helper

Writing interfaces can be annoying. You can save a lot of time when you have to define Typescript interfaces for data that you are loading from a webservice.  Instead of typing all the interfaces yourself you can just use a nice service in the web: json2ts Just paste in your json code and it generates the corresponding interfaces in Typescripts. Example JSON: [   {      "city": "Berlin",     "country": "Germany",     "currencies": [{"code":"EUR"}]   },   {      "city": "Paris",     "country": "France",     "currencies": [{"code":"EUR"}]   } ] Generated code: declare module namespace {     export interface Currency {         code: string;     }     export interface RootObject {         city: string;         country: string;         currencies: Currency...

How to implement a search field in Angular X that starts some action as soon as you stop typing

Everybody knows the Google search that displays some recommendations while you are typing. Some times when you are developing an application you might need a similar functionality for implementing a kind of free text search to quickly find results in a long list of data stored in a database that might be filtered and delivered by a webservice in the background.  The requirement: The search should happen without clicking a button but it should not start right after each single character you have typed. It should wait a short moment and after you have stopped typing immediately start the search. The implementation is quite simple and the same way you could do that in Javascript. First we need to prepare our template to have an input field in which the user can type in a search string.  Whenever the user types a character a function should be called. This is done with the keyup event. (keyup)="searchChanged($event)" In our component we have to defin...