Angular 4 – Downloading file via a service

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.

Add a Comment

Your email address will not be published. Required fields are marked *

*
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