逻辑:传后台需要的参数一般(文件的id和文件的name)请求接口拿到文件流—将文件流转化成blob()对象—生成URL—动态创建a标签—绑定href属性
代码:
// .vue 文件
// 下载按钮
<template #afterRemoveButton="{ record }">
<a @click="download(record)">下载</a>
</template>
// 引入你的请求发Ajax的js文件
import { iopForeignLog } from '@/iop-wg/service/index'
// 下载的执行逻辑
download (record) {
iopForeignLog.download(record.fileId, record.fileName)
.then(res => res.blob()) // 将你请求回来的文件流转换为blob对象
.then(data => {
const blobUrl = window.URL.createObjectURL(data)
const a = document.createElement('a')
a.style.display = 'none'
a.download = record.fileName
a.href = blobUrl
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
})
}
// servise 文件
async download (fileId, fileTile) {
const tooken = Tooken.getToken('WG_EDUMNG') // 获取token(自己项目封装的获取token的方法)
const url = `${path.report.ForeignLog.evryLog.download}?fileId=${fileId}&fileTile=${fileTile}&token=${tooken}`
const result = fetch(url, { // 请求地址
methods: 'GET',
headers: {
'Content-Type': 'application/json',
'Access-Token': tooken
}
})
return result
}
// 又时需要动态拼接参数 方法如下:
async exportFileWg (params) { // params:参数对象
let url = path.personnelMalagement.fieldMan.exportFileWg
if (params) {
const paramsArray = []
// 拼接参数
Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
if (url.search(/\?/) === -1) {
url += '?' + paramsArray.join('&')
} else {
url += '&' + paramsArray.join('&')
}
}
const result = fetch(url, { // 请求地址
methods: 'GET',
headers: {
'Content-Type': 'application/json',
'Access-Token': iopTokenService.getCurrentToken() // 传递token 这里框架封装好了,没有封装需要自己写
}
// body: JSON.stringify(params) post 方式传参数
})
return result
}
版权声明:本文为PaulR原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。