1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| import { Loading, Message } from "element-ui"; import moment from 'moment';
const download = ({ url, // 请求地址 data, // post 请求参数 params, // get 请求参数 method = "post", // 请求方式 filename, // 文件名 loadingText = "正在下载...", // loading 提示文本内容 errorText = "下载失败", // 下载失败时提示文本 handleErr // 自定义文件下载时,系统级抛错时处理函数,非 http 错误 }) => { let loadingInstance = Loading.service({ background: "transparent", fullscreen: true, text: loadingText });
data = data ? JSON.stringify(data) : false;
if (params) { url += '?' + decodeURIComponent( new URLSearchParams( params ) ) }
return new Promise((resolve, reject) => { let x = new XMLHttpRequest(); x.open(method, url, true); if (method === "post" || method === "POST") x.setRequestHeader("content-type", "application/json;charset=utf-8"); x.responseType = "blob"; x.onload = function(e) { let client_msg = errorText, blob = this.response, status = this.status; filename = getFileName( filename , this ) if (status == 504) { client_msg = "网络忒卡,连接超时"; }
loadingInstance.close();
if (status == 200) { if (blob.type.indexOf("application/json") !== -1) { blobToJson(blob).then(res => { handleErr && handleErr(res); }); return; }
if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, filename); } else { let eleLink = document.createElement("a"), objectUrl = URL.createObjectURL(blob); eleLink.setAttribute("download", filename); eleLink.style.display = "none"; eleLink.href = objectUrl; document.body.appendChild(eleLink); eleLink.click(); document.body.removeChild(eleLink); } resolve(); } else { Message.error({ message: client_msg }); reject(e); } };
x.onerror = function(e) { loadingInstance.close(); Message.error({ message: errorText }); reject(e); };
if (data) x.send(data); else x.send(); }); };
function blobToJson(blob) { return new Promise((resolve, reject) => { let reader = new FileReader(); reader.readAsText(blob); reader.onload = e => { let jsonRes = JSON.parse(e.target.result); resolve(jsonRes); }; }); }
function getFileName( customFilename, xhr ){ let name = ''; if ( customFilename ){ name = customFilename }else { let headers = xhr.getResponseHeader('content-disposition') || moment( +new Date() ).format('YMDHmm'), index = headers.search('filename='), start = index === -1 ? 0 : index;
name = decodeURIComponent( headers.slice( start + 9 ) ); }
return name.lastIndexOf('.') !== -1 ? name : ( name + '.xls' ); }
export default download;
|