js-file-downloader
Version:
Small lib for a cool download experience
11 lines • 18.6 kB
JavaScript
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.jsFileDownloader=e():t.jsFileDownloader=e()}(this,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=0)}([function(t,e,r){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function o(t,e){for(var r=0;r<e.length;r++){var o=e[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,(i=o.key,a=void 0,a=function(t,e){if("object"!==n(t)||null===t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var o=r.call(t,e||"default");if("object"!==n(o))return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(i,"string"),"symbol"===n(a)?a:String(a)),o)}var i,a}function i(t,e){if(e&&("object"===n(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function a(t){var e="function"==typeof Map?new Map:void 0;return(a=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,n)}function n(){return u(t,arguments,l(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),s(n,t)})(t)}function u(t,e,r){return(u=c()?Reflect.construct.bind():function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&s(o,r.prototype),o}).apply(null,arguments)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function s(t,e){return(s=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function l(t){return(l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}r.r(e);var f=function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),Object.defineProperty(t,"prototype",{writable:!1}),e&&s(t,e)}(p,t);var e,r,n,a,u,f=(e=p,r=c(),function(){var t,n=l(e);if(r){var o=l(this).constructor;t=Reflect.construct(n,arguments,o)}else t=n.apply(this,arguments);return i(this,t)});function p(t,e){var r;return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,p),(r=f.call(this,"Downloader error: ".concat(t))).request=e,r.name="DownloadException",r}return n=p,a&&o(n.prototype,a),u&&o(n,u),Object.defineProperty(n,"prototype",{writable:!1}),n}(a(Error)),p={"89504E47":"image/png",25504446:"application/pdf"};
/*!
* JS File Downloader v 1.1.25
* https://github.com/AleeeKoi/js-file-downloader
*
* Copyright Alessandro Pellizzari
* Released under the MIT license
* http://opensource.org/licenses/MIT
*/
function h(t){return(h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function d(){/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */d=function(){return t};var t={},e=Object.prototype,r=e.hasOwnProperty,n=Object.defineProperty||function(t,e,r){t[e]=r.value},o="function"==typeof Symbol?Symbol:{},i=o.iterator||"@@iterator",a=o.asyncIterator||"@@asyncIterator",u=o.toStringTag||"@@toStringTag";function c(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{c({},"")}catch(t){c=function(t,e,r){return t[e]=r}}function s(t,e,r,o){var i=e&&e.prototype instanceof p?e:p,a=Object.create(i.prototype),u=new S(o||[]);return n(a,"_invoke",{value:O(t,r,u)}),a}function l(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var f={};function p(){}function y(){}function v(){}var m={};c(m,i,(function(){return this}));var b=Object.getPrototypeOf,w=b&&b(b(P([])));w&&w!==e&&r.call(w,i)&&(m=w);var g=v.prototype=p.prototype=Object.create(m);function k(t){["next","throw","return"].forEach((function(e){c(t,e,(function(t){return this._invoke(e,t)}))}))}function x(t,e){var o;n(this,"_invoke",{value:function(n,i){function a(){return new e((function(o,a){!function n(o,i,a,u){var c=l(t[o],t,i);if("throw"!==c.type){var s=c.arg,f=s.value;return f&&"object"==h(f)&&r.call(f,"__await")?e.resolve(f.__await).then((function(t){n("next",t,a,u)}),(function(t){n("throw",t,a,u)})):e.resolve(f).then((function(t){s.value=t,a(s)}),(function(t){return n("throw",t,a,u)}))}u(c.arg)}(n,i,o,a)}))}return o=o?o.then(a,a):a()}})}function O(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return F()}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var u=E(a,r);if(u){if(u===f)continue;return u}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var c=l(t,e,r);if("normal"===c.type){if(n=r.done?"completed":"suspendedYield",c.arg===f)continue;return{value:c.arg,done:r.done}}"throw"===c.type&&(n="completed",r.method="throw",r.arg=c.arg)}}}function E(t,e){var r=e.method,n=t.iterator[r];if(void 0===n)return e.delegate=null,"throw"===r&&t.iterator.return&&(e.method="return",e.arg=void 0,E(t,e),"throw"===e.method)||"return"!==r&&(e.method="throw",e.arg=new TypeError("The iterator does not provide a '"+r+"' method")),f;var o=l(n,t.iterator,e.arg);if("throw"===o.type)return e.method="throw",e.arg=o.arg,e.delegate=null,f;var i=o.arg;return i?i.done?(e[t.resultName]=i.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,f):i:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,f)}function L(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function j(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function S(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(L,this),this.reset(!0)}function P(t){if(t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,o=function e(){for(;++n<t.length;)if(r.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=void 0,e.done=!0,e};return o.next=o}}return{next:F}}function F(){return{value:void 0,done:!0}}return y.prototype=v,n(g,"constructor",{value:v,configurable:!0}),n(v,"constructor",{value:y,configurable:!0}),y.displayName=c(v,u,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===y||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,v):(t.__proto__=v,c(t,u,"GeneratorFunction")),t.prototype=Object.create(g),t},t.awrap=function(t){return{__await:t}},k(x.prototype),c(x.prototype,a,(function(){return this})),t.AsyncIterator=x,t.async=function(e,r,n,o,i){void 0===i&&(i=Promise);var a=new x(s(e,r,n,o),i);return t.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},k(g),c(g,u,"Generator"),c(g,i,(function(){return this})),c(g,"toString",(function(){return"[object Generator]"})),t.keys=function(t){var e=Object(t),r=[];for(var n in e)r.push(n);return r.reverse(),function t(){for(;r.length;){var n=r.pop();if(n in e)return t.value=n,t.done=!1,t}return t.done=!0,t}},t.values=P,S.prototype={constructor:S,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(j),!t)for(var e in this)"t"===e.charAt(0)&&r.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function n(r,n){return a.type="throw",a.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return n("end");if(i.tryLoc<=this.prev){var u=r.call(i,"catchLoc"),c=r.call(i,"finallyLoc");if(u&&c){if(this.prev<i.catchLoc)return n(i.catchLoc,!0);if(this.prev<i.finallyLoc)return n(i.finallyLoc)}else if(u){if(this.prev<i.catchLoc)return n(i.catchLoc,!0)}else{if(!c)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return n(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n];if(o.tryLoc<=this.prev&&r.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,f):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),f},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),j(r),f}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;j(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:P(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),f}},t}function y(t,e,r,n,o,i,a){try{var u=t[i](a),c=u.value}catch(t){return void r(t)}u.done?e(c):Promise.resolve(c).then(n,o)}function v(t){return function(){var e=this,r=arguments;return new Promise((function(n,o){var i=t.apply(e,r);function a(t){y(i,n,o,a,u,"next",t)}function u(t){y(i,n,o,a,u,"throw",t)}a(void 0)}))}}function m(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function b(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,(o=n.key,i=void 0,i=function(t,e){if("object"!==h(t)||null===t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var n=r.call(t,e||"default");if("object"!==h(n))return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(o,"string"),"symbol"===h(i)?i:String(i)),n)}var o,i}var w={timeout:4e4,headers:[],forceDesktopMode:!1,autoStart:!0,withCredentials:!1,method:"GET",nameCallback:function(t){return t},contentType:"application/x-www-form-urlencoded",body:null,nativeFallbackOnError:!1,contentTypeDetermination:!1},g=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return m(this,t),this.params=Object.assign({},w,e),this.link=this.createLink(),this.request=null,this.downloadedFile=null,this.abortController=void 0,this.params.autoStart?this.downloadFile():this}var e,r,n,o,i;return e=t,(r=[{key:"start",value:function(){return this.downloadFile()}},{key:"abort",value:function(t){this.abortController&&this.abortController.abort(t||"Download cancelled")}},{key:"downloadFile",value:function(){var t=this;return new Promise((function(e,r){t.initDownload(e,r)}))}},{key:"setAbortListner",value:function(t){this.abortController&&this.abortController.signal.addEventListener("abort",t)}},{key:"unsetAbortListner",value:function(t){this.abortController&&this.abortController.signal.removeEventListener("abort",t)}},{key:"initDownload",value:function(t,e){var r=this,n=function(){r.link.target="_blank",r.link.href=r.params.url,r.clickLink()};if(!("download"in this.link)||this.isMobile())return n(),t();this.request=this.createRequest(),this.abortController="AbortController"in window?new AbortController:null;var o=function t(n){var o=n.target;r.unsetAbortListner(t),r.request&&r.request.abort(),e(o.reason)};return this.setAbortListner(o),this.params.url?(this.request.onload=v(d().mark((function n(){return d().wrap((function(n){for(;;)switch(n.prev=n.next){case 0:if(r.unsetAbortListner(o),200===parseInt(r.request.status,10)){n.next=3;break}return n.abrupt("return",e(new f("status code [".concat(r.request.status,"]"),r.request)));case 3:return n.next=5,r.startDownload();case 5:return n.abrupt("return",t(r));case 6:case"end":return n.stop()}}),n)}))),this.request.ontimeout=function(){r.unsetAbortListner(o),e(new f("request timeout",r.request))},this.request.onerror=function(){r.unsetAbortListner(o),r.params.nativeFallbackOnError?(n(),t(r)):e(new f("network error",r.request))},this.request.send(this.params.body),this):e(new f("url param not defined!",this.request))}},{key:"isMobile",value:function(){return!this.params.forceDesktopMode&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}},{key:"createRequest",value:function(){var t=new XMLHttpRequest;return t.open(this.params.method,this.params.url,!0),!1!==this.params.contentType&&t.setRequestHeader("Content-type",this.params.contentType),this.params.headers.forEach((function(e){t.setRequestHeader(e.name,e.value)})),t.responseType="arraybuffer",this.params.process&&"function"==typeof this.params.process&&t.addEventListener("progress",this.params.process),this.params.onloadstart&&"function"==typeof this.params.onloadstart&&(t.onloadstart=this.params.onloadstart),t.timeout=this.params.timeout,t.withCredentials=!!this.params.withCredentials||!!this.params.includeCredentials,t}},{key:"getFileName",value:function(){if("string"==typeof this.params.filename)return this.params.filename;var t=this.request.getResponseHeader("Content-Disposition"),e=[];t&&(e=t.replace(/["']/g,"").match(/filename\*?=([^;]+)/));var r=e&&e.length>=1?e[1]:this.params.url.split("/").pop().split("?")[0];return this.params.nameCallback(r)}},{key:"getContentTypeFromFileSignature",value:function(t){var e=Object.assign({},p,this.params.customFileSignatures);return new Promise((function(r,n){var o=new FileReader,i=t.slice(0,4);o.onloadend=function(t){if(t.target.readyState===FileReader.DONE){var o=new Uint8Array(t.target.result),i=[];o.forEach((function(t){i.push(t.toString(16))}));var a=i.join("").toUpperCase();r(e[a])}else n()},o.onerror=n,o.readAsArrayBuffer(i)}))}},{key:"getContentTypeFromResponseHeader",value:function(){return this.request.getResponseHeader("content-type")}},{key:"getContentType",value:function(t){var e=this;return new Promise(function(){var r=v(d().mark((function r(n){var o,i,a,u,c,s,l,f;return d().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:if(o=e.params.contentTypeDetermination,i="application/octet-stream","header"!==o&&"full"!==o||(a=e.getContentTypeFromResponseHeader()),"signature"!==o&&"full"!==o){r.next=7;break}return r.next=6,e.getContentTypeFromFileSignature(new Blob([t]));case 6:u=r.sent;case 7:n("header"===o?null!==(c=a)&&void 0!==c?c:i:"signature"===o?null!==(s=u)&&void 0!==s?s:i:"full"===o&&null!==(l=null!==(f=u)&&void 0!==f?f:a)&&void 0!==l?l:i);case 8:case"end":return r.stop()}}),r)})));return function(t){return r.apply(this,arguments)}}())}},{key:"createLink",value:function(){var t=document.createElement("a");return t.style.display="none",t}},{key:"clickLink",value:function(){var t;try{t=new MouseEvent("click")}catch(e){(t=document.createEvent("MouseEvent")).initMouseEvent("click",!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,null)}this.link.dispatchEvent(t)}},{key:"getFile",value:(i=v(d().mark((function t(e,r){var n,o,i;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.getContentType(e);case 2:n=t.sent,i={type:n};try{o=new File([e],r,i)}catch(t){(o=new Blob([e],i)).name=r,o.lastModifiedDate=new Date}return t.abrupt("return",o);case 6:case"end":return t.stop()}}),t,this)}))),function(t,e){return i.apply(this,arguments)})},{key:"startDownload",value:(o=v(d().mark((function t(){var e,r;return d().wrap((function(t){for(;;)switch(t.prev=t.next){case 0:return e=this.getFileName(),t.next=3,this.getFile(this.request.response,e);case 3:if(this.downloadedFile=t.sent,!("msSaveOrOpenBlob"in window.navigator)){t.next=6;break}return t.abrupt("return",window.navigator.msSaveOrOpenBlob(this.downloadedFile,e));case 6:return r=window.URL.createObjectURL(this.downloadedFile),this.link.href=r,this.link.download=e,this.clickLink(),setTimeout((function(){(window.URL||window.webkitURL||window).revokeObjectURL(r)}),4e4),t.abrupt("return",this.downloadedFile);case 12:case"end":return t.stop()}}),t,this)}))),function(){return o.apply(this,arguments)})}])&&b(e.prototype,r),n&&b(e,n),Object.defineProperty(e,"prototype",{writable:!1}),t}();e.default=g}]).default}));
//# sourceMappingURL=js-file-downloader.min.js.map