blob: d8c18229c3961850ec17d23178cc41b2cdde61bf [file] [log] [blame]
Michael Landoed64b5e2017-06-09 03:19:04 +03001export class FileUtils {
2
3 static '$inject' = [
4 '$window'
5 ];
6
7 constructor(private $window:any) {
8 }
9
10 public byteCharactersToBlob = (byteCharacters, contentType):any => {
11 contentType = contentType || '';
12 let sliceSize = 1024;
13 let bytesLength = byteCharacters.length;
14 let slicesCount = Math.ceil(bytesLength / sliceSize);
15 let byteArrays = new Array(slicesCount);
16
17 for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
18 let begin = sliceIndex * sliceSize;
19 let end = Math.min(begin + sliceSize, bytesLength);
20
21 let bytes = new Array(end - begin);
22 for (let offset = begin, i = 0; offset < end; ++i, ++offset) {
23 bytes[i] = byteCharacters[offset].charCodeAt(0);
24 }
25 byteArrays[sliceIndex] = new Uint8Array(bytes);
26 }
27 return new Blob(byteArrays, {type: contentType});
28 };
29
30 public base64toBlob = (base64Data, contentType):any => {
31 let byteCharacters = atob(base64Data);
32 return this.byteCharactersToBlob(byteCharacters, contentType);
33 };
34
35 public downloadFile = (blob, fileName):void=> {
36 let url = this.$window.URL.createObjectURL(blob);
37 let downloadLink = document.createElement("a");
38
39 downloadLink.setAttribute('href', url);
40 downloadLink.setAttribute('download', fileName);
41 document.body.appendChild(downloadLink);
42
43 var clickEvent = new MouseEvent("click", {
44 "view": window,
45 "bubbles": true,
46 "cancelable": true
47 });
48 downloadLink.dispatchEvent(clickEvent);
49
50 }
51}