Home » Featured, Headline, Software Development

Angular 4 – Downloading file via a service

5 October 2017 No Comment

In most projects, a download service is required for file downloads. This post entails downloading a file via a backend service.

1. Install the dependencies, file-saver and the types
Assumption: Typescript is used for Angular code

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

2.Create a FileService and add a download() function to get the document

@Injectable()
export class FileService{

  private DOCUMENT_API_PATH= '/api/getDocument';
  
  download(documentId: string): Observable<any> {
    // set headers for the file and response to be Blob
    const headers = new Headers({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({ headers: headers });
    options.responseType = ResponseContentType.Blob;

    return this.http.get(`${this.DOCUMENT_API_PATH}/${documentId}`, options)
      .map((res: Response) => res)
      .catch(this.handleError);
  }
  // handle error
  private handleError (error: any) {
    return Observable.throw(error);
  }
}

3. Call the fileService download() in the component to download the file. This will save the file locally.

this.fileService.download(documentId)
  .subscribe(
    (response: any) => {
      // get the response as blob, rename the file, and save  it
      const blob = response.blob();
      const file = new Blob([blob], {});
      const filename = 'document-' + Date.now() + '.pdf';
      FileSaver.saveAs(file, filename);
    },
    error => {
      alert('The file is not available');
    },
    () => {}
  );

Hope this is helpful.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image