JS按钮直接下载文件函数封装
2021-02-25 21:33:45
// JS下载文件函数
// download(url,filename);
function download(url,fname) {
ajax(url, function(xhr) {
var filename = fname+'.' + url.replace(/(.*\.)/, '') // 自定义文件名+后缀
downloadFile(xhr.response, filename)
}, {
responseType: 'blob'
})
}
function downloadFile(content, filename) {
var a = document.createElement('a')
var blob = new Blob([content])
var url = window.URL.createObjectURL(blob)
a.href = url
a.download = filename
a.click()
window.URL.revokeObjectURL(url)
}
function ajax(url, callback, options) {
window.URL = window.URL || window.webkitURL
var 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()
}
// JS下载文件函数
// download(url,filename);