UNPKG

vuexcel-utils

Version:
91 lines (83 loc) 2.61 kB
/** * 下载系统的解决方案 * @Author OfficeDev * @todo check * */ import * as FileSaver from 'file-saver' /* For all Office clients and browsers, except Safari, the user gets prompted to save the file. In Safari, the file is opened in another tab and the user manually chooses where to save the file. */ export default function downloader(downloadUri: string, name: string) { // The following line is taken from http://stackoverflow.com/questions/7944460/detect-safari-browser // if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { if (/^((?!chrome|android).)*(safari|AppleWebKit)/i.test(navigator.userAgent)) { insertAndClickLink(downloadUri, name); } else if (navigator.userAgent.indexOf("AppleWebKit") > -1) { insertAndClickLink(downloadUri, name); } else { // First download the file, then prompt the user to save it. // This function uses the file-saver.js library. getFile(downloadUri) .then(function (file: any) { FileSaver.saveAs(file, name); }) .catch(function (e: Error) { console.error(e); }); } } /* Downloads the file from the remote server. */ function getFile(url: string) { return new Promise(function (resolve: Function, reject: Function) { // Use XHR to fetch the file from the remote server. var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.onload = function () { try { if (xhr.status === 200) { resolve(xhr.response); } else if (xhr.status !== 200) { reject({ error: 'Request failed. ' + xhr.response }); } } catch (e) { reject({ error: e }); } }; xhr.send(); }); } /* The following solution programmatically inserts a link and clicks it. Use with Safari browsers. */ function insertAndClickLink(downloadUri: string, fileName: string) { //Taken from http://stackoverflow.com/questions/3077242/force-download-a-pdf-link-using-javascript-ajax-jquery/29266135#29266135 try { if (!(<any>window).ActiveXObject) { var save = document.createElement('a'); save.href = downloadUri; save.target = '_blank'; save.download = fileName || 'output'; var evt = new MouseEvent('click', { 'view': window, 'bubbles': true, 'cancelable': false }); save.dispatchEvent(evt); (window.URL || (<any>window).webkitURL).revokeObjectURL(save.href); } } catch (e) { console.error(e); } }