/**
- ajax 文件下载
- @param {Object} config 下载的文件配置 url、timeout、callback
- 返回请求成功或失败
*/
export function fileDownload (config) {
var xhr = new XMLHttpRequest()
var dataPath = config.url
xhr.open('GET', dataPath)
// xhr.onprogress = function (event) {
// console.log(event)
// // console.log(Math.round((event.loaded / event.total) * 100) + '%')
// }
xhr.responseType = 'arraybuffer'
xhr.timeout = config.timeout || 1 * 60 * 1000
xhr.addEventListener('readystatechange', function (event) {
// console.log(event)
if (xhr.status === 200 && xhr.readyState === 4) {
var contentDisposition = xhr.getResponseHeader('Content-disposition')
var contentType = xhr.getResponseHeader('Content-type')
var blob = new Blob([xhr.response], {
type: contentType
})
var url = window.URL.createObjectURL(blob)
var regex = /filename=[^;]*/
var matchs = contentDisposition.match(regex)
var filename = ''
if (matchs) {
filename = decodeURIComponent(matchs[0].split('=')[1])
} else {
filename = +Date.now() + '.xlsx'
}
var a = document.createElement('a')
a.href = url
a.download = filename
a.click()
window.URL.revokeObjectURL(url)
config.callBack && config.callBack(true)
}
})
xhr.ontimeout = function () {
// console.log('timeout...')
config.callBack && config.callBack(false)
}
xhr.withCredentials = true
xhr.send()
}
网友评论