UNPKG

billie-util

Version:

a gatjer of utils to improve develop efficiency

37 lines (32 loc) 1.23 kB
/** * 传入一个文件下载路径,将文件下载到本地 */ const isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; const isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; const download = function (sUrl) { //If in Chrome or Safari - download via virtual link click if (isChrome || isSafari) { //Creating new link node. var link = document.createElement('a'); link.href = sUrl; if (link.download !== undefined) { //Set HTML5 download attribute. This will prevent file from opening if supported. var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length); link.download = fileName; } //Dispatching click event. if (document.createEvent) { var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); link.dispatchEvent(e); return true; } } // Force file download (whether supported by server). if (sUrl.indexOf('?') === -1) { sUrl += '?download'; } window.open(sUrl, '_self'); return true; } module.exports = download