1.下载功能
// 下载需要ID 使用插槽传递ID
<el-button @click="downLoadEXCEL(scope.row.id)"></el-button>
// 下载功能
downLoadEXCEL(id: number) {
downloadMemberExcel(id).then(res => {
if (res) {
const blob = new Blob([res.data]);
// 对于<a>标签,只有 Firefox 和 Chrome(内核) 支持 download 属性
// IE10以上支持blob但是依然不支持download
if ('download' in document.createElement('a')) {
// 支持a标签download的浏览器
const link = document.createElement('a')// 创建a标签
link.download = '文件名.xlsx'// a标签添加属性
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()// 执行下载
URL.revokeObjectURL(link.href) // 释放url
document.body.removeChild(link)// 释放标签
} else {
navigator.msSaveBlob(blob, '文件名.xlsx')
}
}
})
}
2.上传功能
<el-upload
class="upload"
ref="upload"
action
accept=".xls,.xlsx"
:limit="1" //限制个数
:auto-upload = "false"
:show-file-list="false"
:on-change="handleChange" //绑定的事件
>
<el-button @click="uploadId(scope.row.id)">上传</el-button>
</el-upload>
// 点击上传,将ID保存
uploadIdBtn(id: number) {
this.uploadId = id
}
// 点击上传excel文件
private handleChange(file: any) {
uploadExcel(file.raw, this.uploadId).then(({ data: res }:any) => {
if (res.code === 0) {
this.$message.success(res.msg)
}
})
}
// 对应的接口
// 上传文件
export function uploadExcel(file: any, id: number) {
const data = new FormData()
data.append('file', file)
return request({
url: `/baseData/uploadExcel/${id}`,
method: 'post',
data: data,
headers: {
'content-type': 'multipart/form-data'
}
})
}
// 下载
export function downloadMemberExcel(id: any) {
return request({
url: `/baseData/downloadDataProfile/${id}`,
method: 'get',
responseType: 'blob'
})
}
================================
另一种上传excel的
// 导入上传
export function importProductExcel(file, uid) {
const data = new FormData()
data.append('file', file)
data.append('uid', uid)
return request({
url: '/product/importProductExcel',
method: 'POST',
data: data,
headers: { 'Content-Type': 'multipart/purchase-data; charset=utf-8' }
})
}
-----------vue
// 上传
onChangeUpload(file) {
console.log(this.$store.state.user.userId)
importProductExcel(file.raw, this.$store.state.user.userId).then(res => {
console.log(res)
if (res.data.code !== 0) return this.$message.error(res.data.msg)
this.$message.success(res.data.msg)
})
}