js 文件下载 blob
最编程
2024-07-17 13:42:25
...
// 判断是否有这个属性
const createObjectURL = function (object) {
return window.URL
? window.URL.createObjectURL(object)
: window.webkitURL.createObjectURL(object)
}
// 使用promise判断是否是文件流
const checkBlob = function (blob) {
return new Promise<void>((resolve, reject) => {
const fileReader = new FileReader()
fileReader.onload = function (res: any) {
const data =
res.target.result.substr(0, 1) == '{'
? JSON.parse(res.target.result)
: { success: true }
if (!data.success) {
reject(data.msg)
} else {
resolve()
}
}
fileReader.readAsText(blob)
})
}
// 文件下载的主体方法
// callback是文件下载成功后的回调函数
//
app.config.globalProperties.blobFileDownLoad = function (
params,
callback
) {
if (!params.method) params.method = 'get'
const xhr = new XMLHttpRequest()
xhr.open(params.method, params.url, true)
xhr.setRequestHeader(
'Authorization',
'Bearer ' + store.state.login.accessToken
)
xhr.responseType = 'blob'
xhr.onload = function (e) {
if (this.status == 200) {
const blob = this.response
checkBlob(blob)
.then(() => {
const filename = params.name + '.xls'
const _window: any = window
if (_window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename)
} else {
const a = document.createElement('a')
const url = createObjectURL(blob)
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
}
})
.catch(err => {
window.$message.error(err)
})
callback()
}
}
xhr.setRequestHeader('Content-type', 'application/json')
xhr.send(params.data)
}
推荐阅读
-
node.js 下载和安装以及环境配置超级详细教程 [Windows 版本]。
-
msvcr100.dll 丢失解决方案,如何安全下载 msvcr100.dll 文件:完整指南
-
从远程 Windows 共享目录读取文件 + 解析后缀为 .mdb 的文件 - 两种下载文件的方法:jcifs、smbj
-
vue 实现文件预览和文件上传、下载、预览 - 多图、模型、dwg 图纸、文档(word、excel、ppt、pdf)
-
浏览器服务器端文件下载控制(安全拦截、文件浏览器打开或下载行为控制)
-
主机文件和 Mac 版 switchhosts 下载
-
自动解压压缩文件并下载安装autodl工具
-
实现纯前端下载PDF链接文件的解决方案,不进行预览操作
-
将Azure Blob容器与本地文件系统进行连接
-
IE浏览器提示当前安全设置不允许下载该文件