import { useDownloadByBase64 } from '@/utils/transform'
const handleDownload = (id: string) => {
version_download({ id }).then(res => {
if (res.file) return useDownloadByBase64(res.file, fileName)
return ToastUtils.error('文件不存在')
})
}
utils/transform.ts
export function useDownloadByBase64(
text: string,
fileName: string,
type = 'application/x-tar'
) {
console.log('fileName: ', fileName)
const at = `data:${type};base64,${text}`
const blob = dataURLtoBlob(at)
const href = window.URL.createObjectURL(blob)
const aLink = document.createElement('a')
aLink.href = href
aLink.download = '测试版本'
aLink.style.display = 'none'
document.body.appendChild(aLink)
aLink.click()
document.body.removeChild(aLink)
window.URL.revokeObjectURL(href)
}
function dataURLtoBlob(dataUrl: string) {
const arr = (dataUrl ?? '').split(',')
const mime = arr[0].match(/:(.*?);/)![1]
console.log('arr: ', arr, mime)
const str = window.atob(arr[1])
let n = str.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = str.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}