/**
* 文件下载方法(支持任何格式文件)
* fileUrl 文件路径,fileName 下载后的文件新名
*/
function fileDownloadFun(fileUrl,fileName) {
if("undefined" == typeof fileUrl || !fileUrl){
alert('文件路径不能为空');return false;
}
let fileUrlArr = fileUrl.split('.');
let fileFix = "undefined" != typeof fileUrlArr[1] && fileUrlArr[1] ? '.' + fileUrlArr[1] : '';
fileName = fileName+fileFix;
// 发送http请求,将文件链接转换成文件流
fileAjaxFun(fileUrl, function(xhr) {
downloadFun(xhr.response, fileName)
}, {
responseType: 'blob'
});
// 发起请求
function fileAjaxFun(url, callback, options) {
let xhr = new XMLHttpRequest()
xhr.open('get', url, true)
if (options.responseType) {
xhr.responseType = options.responseType
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr)
}
}
xhr.send();
}
// 进行下载
function downloadFun(content, filename) {
window.URL = window.URL || window.webkitURL
let a = document.createElement('a')
let blob = new Blob([content])
// 通过二进制文件创建url
let url = window.URL.createObjectURL(blob)
a.href = url
a.download = filename
a.click()
// 销毁创建的url
window.URL.revokeObjectURL(url);
}
}
/**
* 文件下载调用示例(支持任何格式文件)
*/
var filePath = 'test.zip';
var fileNewName = '测试文件';
fileDownloadFun(filePath,fileNewName);
模拟ajax提交生成文件流进行下载(未知文件类型,支持所有类型文件直接下载)
最新推荐文章于 2023-11-23 17:14:02 发布