通过get请求下载excel文件有个限制是请求参数长度受限,改为post方式获取excel文件流到页面实现。
方式一:JQ实现
function downLoadFile(options) {
$.ajax({
type: 'POST',
url : options.url,
data: options.data,
complete: function( xhr,data ){
var fileName = xhr.getResponseHeader("Content-Disposition").split(";")[1].split("filename=")[1];
var fileNameUnicode = xhr.getResponseHeader("Content-Disposition").split("filename*=")[1];
if (fileNameUnicode) {
fileName = decodeURIComponent(fileNameUnicode.split("''")[1]);
}
var blob = new Blob([xhr.response], { type: "application/vnd.ms-excel" });
//var blob = new Blob([ajaxRequest.response], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = objectUrl;
a.download = fileName;
a.click();
document.body.removeChild(a);
}
});
}
方式二:原生js实现
function downLoadFile(options) {
var sendData = JSON.stringify(options.data);
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.responseType = 'arraybuffer';
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var fileName = ajaxRequest.getResponseHeader("Content-Disposition").split(";")[1].split("filename=")[1];
var fileNameUnicode = ajaxRequest.getResponseHeader("Content-Disposition").split("filename*=")[1];
if (fileNameUnicode) {
fileName = decodeURIComponent(fileNameUnicode.split("''")[1]);
}
var blob = new Blob([ajaxRequest.response], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = objectUrl;
a.download = fileName;
a.click();
document.body.removeChild(a);
}
else if (ajaxRequest.status == 409 || ajaxRequest.status == 500 || ajaxRequest.status == 204) {
//alert(ajaxRequest.status);
}
}
ajaxRequest.open("POST", options.url, true);
ajaxRequest.setRequestHeader("Content-Type", "application/json");
ajaxRequest.send(sendData);
}
调用参数option数据结构为{url:'post请求的服务器路径',data:'post的参数json结构'}