blob: d726736bd449792de7a0914b379f1e000dc586e6 [file] [log] [blame]
Michael Landodd603392017-07-12 00:54:52 +03001/*-
2 * ============LICENSE_START=======================================================
3 * SDC
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
19 */
20
Michael Landoed64b5e2017-06-09 03:19:04 +030021export class FileUtils {
22
23 static '$inject' = [
24 '$window'
25 ];
26
27 constructor(private $window:any) {
28 }
29
30 public byteCharactersToBlob = (byteCharacters, contentType):any => {
31 contentType = contentType || '';
32 let sliceSize = 1024;
33 let bytesLength = byteCharacters.length;
34 let slicesCount = Math.ceil(bytesLength / sliceSize);
35 let byteArrays = new Array(slicesCount);
36
37 for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
38 let begin = sliceIndex * sliceSize;
39 let end = Math.min(begin + sliceSize, bytesLength);
40
41 let bytes = new Array(end - begin);
42 for (let offset = begin, i = 0; offset < end; ++i, ++offset) {
43 bytes[i] = byteCharacters[offset].charCodeAt(0);
44 }
45 byteArrays[sliceIndex] = new Uint8Array(bytes);
46 }
47 return new Blob(byteArrays, {type: contentType});
48 };
49
50 public base64toBlob = (base64Data, contentType):any => {
51 let byteCharacters = atob(base64Data);
52 return this.byteCharactersToBlob(byteCharacters, contentType);
53 };
54
55 public downloadFile = (blob, fileName):void=> {
56 let url = this.$window.URL.createObjectURL(blob);
57 let downloadLink = document.createElement("a");
58
59 downloadLink.setAttribute('href', url);
60 downloadLink.setAttribute('download', fileName);
61 document.body.appendChild(downloadLink);
62
63 var clickEvent = new MouseEvent("click", {
64 "view": window,
65 "bubbles": true,
66 "cancelable": true
67 });
68 downloadLink.dispatchEvent(clickEvent);
69
70 }
71}