/**
* a标签下载
*
* @param {*} url 链接
* @param {*} options 参数 { payload: url携带参数 }
* @returns {Boolean} success
*/
export function downloadByLink(url, options) {
if (!url) return false
const a = document.createElement('a')
// 添加属性
let href = url
const {
payload,
...attrs
} = options || {}
attrs.href = payload ? (href += '?' + qs.stringify(payload)) : href
Object.entries(attrs).forEach(([key, value]) => {
a.setAttribute(key, value)
})
a.setAttribute('target', '_self')
// 触发下载
document.body.appendChild(a)
a.click()
a.onclick = e => {
e && e.preventDefault()
}
a.parentNode.removeChild(a)
return true
}
加载script
/**
* 加载脚本
*
* @param {String} src 地址
* @param {*} options 属性 { autoremove: 用完就扔, ... }
*
* @returns {Promise}
*
* @throws {Error}
*/
export function loadScript(src, options) {
const {
autoremove = true, ...attrs
} = options || {}
return new Promise((resolve, reject) => {
const script = document.createElement('script')
Object.entries(attrs).forEach(([key, val]) => {
script.setAttribute(key, val)
})
script.src = src
script.onload = () => {
if (autoremove) {
script.onload = script.onerror = null
document.head.removeChild(script)
}
resolve()
}
script.onerror = reject
document.head.appendChild(script)
})
}
Blob文件转换下载
// Blob文件转换下载
export const downBlobFile = (result, fileName, fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;', submitEndDo ? , timeSuffix = true) => {
const data = result
const blob = new Blob([data], {
type: fileType
})
if (timeSuffix) {
// 默认导出的文件名称添加时间
const time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
fileName = fileName + ' ' + time
}
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
// for IE
// IE必须给文件名设置固定后缀,不然默认会是.txt
window.navigator.msSaveOrOpenBlob(blob, fileName + '.xlsx')
} else {
// for Non-IE (chrome, firefox etc.)
const objectUrl = URL.createObjectURL(blob)
const a = document.createElement('a')
a.setAttribute('style', 'display:none')
a.setAttribute('href', objectUrl)
a.setAttribute('download', fileName)
a.click()
URL.revokeObjectURL(objectUrl)
}
if (submitEndDo) {
submitEndDo()
submitEndDo = null
}
}