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
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文件转换下载
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) {
window.navigator.msSaveOrOpenBlob(blob, fileName + '.xlsx')
} else {
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
}
}