|
| 1 | +/* |
| 2 | +substantial portions of this code from FileSaver.js |
| 3 | +https://github.com/eligrey/FileSaver.js |
| 4 | +License: https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md |
| 5 | +*/ |
| 6 | + |
| 7 | +/* FileSaver.js |
| 8 | + * A saveAs() FileSaver implementation. |
| 9 | + * 1.1.20160328 |
| 10 | + * |
| 11 | + * By Eli Grey, http://eligrey.com |
| 12 | + * License: MIT |
| 13 | + * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md |
| 14 | + */ |
| 15 | + |
| 16 | + |
| 17 | +'use strict'; |
| 18 | + |
| 19 | +var saveLink = document.createElementNS("http://www.w3.org/1999/xhtml", "a"); |
| 20 | +var canUseSaveLink = "download" in saveLink; |
| 21 | +var isSafari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent); |
| 22 | + |
| 23 | +var fileSaver = function(url, name) { |
| 24 | + var promise = new Promise(function(resolve, reject) { |
| 25 | + // IE <10 is explicitly unsupported |
| 26 | + if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { |
| 27 | + reject(new Error("IE < 10 unsupported")); |
| 28 | + } |
| 29 | + |
| 30 | + // First try a.download, then web filesystem, then object URLs |
| 31 | + if (isSafari) { |
| 32 | + // Safari doesn't allow downloading of blob urls |
| 33 | + document.location.href = "data:attachment/file" + url.slice(url.search(/[,;]/)); |
| 34 | + resolve(name); |
| 35 | + } |
| 36 | + |
| 37 | + if (!name) { |
| 38 | + name = "download"; |
| 39 | + } |
| 40 | + |
| 41 | + if (canUseSaveLink) { |
| 42 | + saveLink.href = url; |
| 43 | + saveLink.download = name; |
| 44 | + document.body.appendChild(saveLink); |
| 45 | + saveLink.click(); |
| 46 | + document.body.removeChild(saveLink); |
| 47 | + resolve(name); |
| 48 | + } |
| 49 | + |
| 50 | + // IE 10+ (native saveAs) |
| 51 | + if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { |
| 52 | + navigator.msSaveOrOpenBlob(url, name); |
| 53 | + resolve(name); |
| 54 | + } |
| 55 | + |
| 56 | + reject(new Error('download error')); |
| 57 | + }); |
| 58 | + |
| 59 | + return promise; |
| 60 | +}; |
| 61 | + |
| 62 | +module.exports = fileSaver; |
0 commit comments