<a class="downfile" href="javascript:;" fileName="abcdef.pdf">简历下载</a>
<a class="downfile" href="javascript:;" fileName="abcdef.doc">简历下载</a>
$(function(){
$('.downfile').on('click', function(){
var url = $(this).attr('fileName')
var arr = url.split('.');
var name = '简历.'+ arr[arr.length-1]
downfile(url, name)
})
})
function downfile(url, name){
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = "blob"; // 返回类型blob
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function() {
// 请求完成
if(this.status === 200) {
// 返回200
var blob = this.response;
var href = window.URL.createObjectURL(blob); //创建下载的链接
//判断是否是IE浏览器,是的话返回true
if (window.navigator.msSaveBlob) {
try {
window.navigator.msSaveBlob(blob, name)
} catch (e) {
console.log(e);
}
}else {
// 谷歌浏览器 创建a标签 添加download属性下载
var downloadElement = document.createElement('a');
downloadElement.href = href;
downloadElement.target = '_blank';
downloadElement.download = name; //下载后文件名
document.body.appendChild(downloadElement);
downloadElement.click(); //点击下载
document.body.removeChild(downloadElement); //下载完成移除元素
window.URL.revokeObjectURL(href); //释放掉blob对象
}
}
}
// 发送ajax请求
xhr.send()
}