ajax下载Excel文件
- GET请求
window.location.href = "http://localhost:8080/xx/map/mapdownlind.action?time1="+time1+"&time2="+time2;
- POST请求
因为ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的,而文件的下载是以二进制形式进行的,所以ajax无法处理二进制流的response来下载文件,只能通过原生ajax的方法进行下载
var xhr = new XMLHttpRequest(); //创建新的XHR对象
var url = "http://localhost:8080/xx/map/mapdownlind.action";
xhr.open('post', url); //指定获取数据的方式和url地址
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); //设置请求头(不同属性值传递的方式不同)
xhr.responseType = 'blob'; //以blob的形式接收数据,一般文件内容比较大
xhr.onload = function() {
var content = this.response; //Blob数据
var elink = document.createElement('a'); // 创建一个a标签用于下载
elink.download = "名字.xlsx"; //规定被下载的超链接目标名字
elink.style.display = 'none'; //标签隐藏
var blob = new Blob([content]);
elink.href = URL.createObjectURL(blob); //规定链接指向的页面的URL
document.body.appendChild(elink);
elink.click(); //原生dom触发
document.body.removeChild(elink);
};
xhr.send("time1="+time1+"&time2="+time2); //post请求传的参数
更多推荐
ajax下载Excel文件
发布评论