参考地址: https://www.cnblogs.com/jackson-yqj/p/11321275.html
/*** 文件链接转文件流下载--主要针对pdf 解决谷歌浏览器a标签下载pdf直接打开的问题* @param url :文件链接* @param fileName :文件名;* @param type :文件类型;*/function fileLinkToStreamDownload(url, fileName, type) {let reg = /^([hH][tT]{2}[pP]:\/\/|[hH][tT]{2}[pP][sS]:\/\/)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\/])+$/;if (!reg.test(url)) {throw new Error("传入参数不合法,不是标准的文件链接");} else {let xhr = new XMLHttpRequest();xhr.open('get', url, true);xhr.setRequestHeader('Content-Type', `application/${type}`);xhr.responseType = "blob";xhr.onload = function () {if (this.status == 200) {//接受二进制文件流var blob = this.response;downloadExportFile(blob, fileName, type)}}xhr.send();}}
/***下载导出文件* @param blob :返回数据的blob对象或链接* @param tagFileName :下载后文件名标记* @param fileType :文件类 word(docx) excel(xlsx) ppt等*/
function downloadExportFile(blob, tagFileName, fileType) {let downloadElement = document.createElement('a');let href = blob;if (typeof blob == 'string') {downloadElement.target = '_blank';} else {href = window.URL.createObjectURL(blob); //创建下载的链接}downloadElement.href = href;downloadElement.download = tagFileName + moment(new Date().getTime()).format('YYYYMMDDhhmmss') + '.' + fileType; //下载后文件名document.body.appendChild(downloadElement);downloadElement.click(); //点击下载document.body.removeChild(downloadElement); //下载完成移除元素if (typeof blob != 'string') {window.URL.revokeObjectURL(href); //释放掉blob对象}}
/*** base64对象转文件对象* @param urlData :数据的base64对象* @param type :类型 image/png;* @returns {Blob}:Blob文件对象*/
function base64ToBlob(urlData, type) {let arr = urlData.split(',');let array = arr[0].match(/:(.*?);/)let mime = (array && array.length > 1 ? array[1] : type) || type;// 去掉url的头,并转化为bytelet bytes = window.atob(arr[1]);// 处理异常,将ascii码小于0的转换为大于0let ab = new ArrayBuffer(bytes.length);// 生成视图(直接针对内存):8位无符号整数,长度1个字节let ia = new Uint8Array(ab);for (let i = 0; i < bytes.length; i++) {ia[i] = bytes.charCodeAt(i);}return new Blob([ab], {type: mime});
}