import { Injectable } from '@angular/core'; import * as _ from 'lodash'; import { UserService } from '../../service/common/user.service'; @Injectable() export class DownloadHelperService { private addressFileNameDictionary = {}; constructor(private user: UserService) { (window).downloadHelperService = this; (window).originalOpen = window.open; (window).open = this.openDecorator; } public registerDownloadLink(urlPart: string, fileName: string) { this.addressFileNameDictionary[urlPart] = fileName; } private openDecorator(url, name, features) { let context: DownloadHelperService = (window).downloadHelperService; let fileName = context.findFileNameByUrl(context, url); if (fileName !== null) { context.downloadViaBlob(context, url, fileName); } else { return (window).originalOpen(url, name, features); } } private findFileNameByUrl(context:DownloadHelperService, url: string): string { for (var key in context.addressFileNameDictionary) { if (url.indexOf(key) !== -1) { return context.addressFileNameDictionary[key]; } } return null; } private downloadViaBlob(context:DownloadHelperService, url: string, fileName: string) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.setRequestHeader("Authorization", "Bearer " + context.user.authentication.accessToken); xhr.responseType = 'blob'; xhr.onload = function() { let response = (this); if (response.status == 200) { var blob = response.response; var div = document.getElementById('fileLoader'); var windowUrl = window.URL || (window).webkitURL; div.style.display = 'block'; var url = windowUrl.createObjectURL(blob); var link = document.createElement('a'); link.href = url; link.download = fileName + context.getExtensionByContentType(response.getResponseHeader('content-type')); if (fileName === "EngineerResult") { link.download = fileName + ".zip"; } document.body.appendChild(link); link.click(); document.body.removeChild(link); windowUrl.revokeObjectURL(url); var div = document.getElementById('fileLoader'); div.style.display = 'none'; } }; xhr.send(); } private getExtensionByContentType(contentType: string): string { switch(contentType) { case 'application/pdf': return '.pdf'; case 'application/vnd.ms-excel': return '.xls'; case 'image/tiff': return '.tif'; case 'application/zip': return '.zip'; default: return ''; } } }