blob: 990701c6f075c7e96b20e927b527c9e014a6d551 [file] [log] [blame]
ilanap1965d162018-01-04 11:34:59 +02001/*
2 * Copyright © 2016-2017 European Support Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17function getTimestampString() {
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020018 let date = new Date();
19 let z = n => (n < 10 ? '0' + n : n);
20 return `${date.getFullYear()}-${z(date.getMonth())}-${z(
21 date.getDate()
22 )}_${z(date.getHours())}-${z(date.getMinutes())}`;
ilanap1965d162018-01-04 11:34:59 +020023}
24
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020025export default function showFileSaveDialog({
26 blob,
27 headers,
28 defaultFilename,
29 addTimestamp
30}) {
31 let filename;
32 let contentDisposition = headers['content-disposition']
33 ? headers['content-disposition']
34 : '';
35 let match = contentDisposition
36 ? contentDisposition.match(/filename=(.*?)(;|$)/)
37 : false;
38 if (match) {
39 filename = match[1];
40 } else {
41 filename = defaultFilename;
42 }
ilanap1965d162018-01-04 11:34:59 +020043
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020044 if (addTimestamp) {
45 filename = filename.replace(
46 /(^.*?)\.([^.]+$)/,
47 `$1_${getTimestampString()}.$2`
48 );
49 }
ilanap1965d162018-01-04 11:34:59 +020050
Einav Weiss Keidar7fdf7332018-03-20 14:45:40 +020051 let link = document.createElement('a');
52 let url = URL.createObjectURL(blob);
53 link.href = url;
54 link.download = filename;
55 link.style.display = 'none';
56 document.body.appendChild(link);
57 link.click();
58 setTimeout(function() {
59 document.body.removeChild(link);
60 URL.revokeObjectURL(url);
61 }, 0);
62}