ilanap | 1965d16 | 2018-01-04 11:34:59 +0200 | [diff] [blame] | 1 | /* |
| 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 | |
| 17 | function getTimestampString() { |
Einav Weiss Keidar | 7fdf733 | 2018-03-20 14:45:40 +0200 | [diff] [blame^] | 18 | 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())}`; |
ilanap | 1965d16 | 2018-01-04 11:34:59 +0200 | [diff] [blame] | 23 | } |
| 24 | |
Einav Weiss Keidar | 7fdf733 | 2018-03-20 14:45:40 +0200 | [diff] [blame^] | 25 | export 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 | } |
ilanap | 1965d16 | 2018-01-04 11:34:59 +0200 | [diff] [blame] | 43 | |
Einav Weiss Keidar | 7fdf733 | 2018-03-20 14:45:40 +0200 | [diff] [blame^] | 44 | if (addTimestamp) { |
| 45 | filename = filename.replace( |
| 46 | /(^.*?)\.([^.]+$)/, |
| 47 | `$1_${getTimestampString()}.$2` |
| 48 | ); |
| 49 | } |
ilanap | 1965d16 | 2018-01-04 11:34:59 +0200 | [diff] [blame] | 50 | |
Einav Weiss Keidar | 7fdf733 | 2018-03-20 14:45:40 +0200 | [diff] [blame^] | 51 | 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 | } |