介绍:封装的二进制流文件下载,简单好用,两步搞定
1.创建 common.js
/**
* 通过流下载文件
* @param {流数据} data
* @param {文件名} name
* @param {文件后缀} suffix
*/
export function downloadFile(data, name, suffix) {
if (window.navigator && window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(new Blob([data]), name + (suffix ? ('.' + suffix) : ''))
} else {
const url = window.URL.createObjectURL(new Blob([data]))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
const fileName = name + (suffix ? ('.' + suffix) : '')
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
2.组件使用
import { downloadFile } from '@/utils/common'
const res = await getDownloadFile(scriptId)
if (res) {
downloadFile(res, scriptName, 'py')
}