使用axios文件下载
if (tableDataSource.selectedRowKeys.length > 0) {
//本次请求你携带token
axios.defaults.headers[
'authorization'
] = `Bearer ${store.state.login.accessToken}`
//你携带的token
axios.defaults.headers['tenantId'] =
store.state.login.tempTenant.id || ''
axios
.post(
window.globalConfig.baseUrl +
'/asset-manage-api/api/manage/asset/aa/bb', //你请求的地址
tableDataSource.selectedRowKeys, //你携带的数组
{
responseType: 'blob', // blob流进行下载
}
)
.then(res => {
let blob = new Blob([res.data], {
type: 'applicationnd.ms-excel',
})
if (!!window.ActiveXObject || 'ActiveXObject' in window) {
window.navigator.msSaveOrOpenBlob(blob, 'fileName')
} else {
const link = document.createElement('a')
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
link.setAttribute('download', 'fileName')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
})
} else {
alert("请选择")
}
使用原生js下载文件
// 判断是否有这个属性
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)
}
使用pots的方式进行下载
proxy.blobFileDownLoad(
{
url:
window.globalConfig.baseUrl +
'/asset-manage-api/api/manage/asset/aa/bb',
method: 'post',
// 需要转化一下哈
data: JSON.stringify(tableDataSource.selectedRowKeys),
},
() => {
// 成功后的回调
console.log(1)
}
)
使用get的方式进行下载哈
function downLoad(type) {
proxy.blobFileDownLoad(
{
url:
window.globalConfig.baseUrl +
'/asset-manage-api/api/manage/asset/cc/qq?type=' +
type,
name:'文件名'
},
() => {
console.log(1)
}
)
}