vue+element/upload 导入/导出

本文详细介绍了一种前后端一体化解决方案,通过具体代码示例展示了如何实现文件的上传与导出功能。涵盖了前端Vue框架下element UI组件库的el-upload和el-button组件的使用,以及后端响应的处理,包括文件流的导出和文件名的正确解析。
1.导入
/*html片段*/

<el-upload
class="upload"
action="" // action是必填项,自定义导出给action制空
:http-request="uploadSectionFile" // 使用http-request自定义导入内容
:show-file-list="false"
>
<el-button
class="in-item"
type="primary"
icon="el-icon-upload"
@click="handleEntrance"
>
导入
</el-button>
</el-upload>
/*js片段*/

uploadSectionFile(file) { // file导入文件
if (file) {
uploadHospital(file).then(res => { // uploadHospital为自定义接口
if (Number(res.code) === 1) {
this.$message({
message: res.data,
type: 'success'
})
}
})
}
},
// 导入
handleEntrance() {
this.uploadSectionFile()
},

/*自定义接口*/

export function uploadHospital(fileobj) {
const param = new FormData() // 上传文件为forData类型
param.append('excelFile', fileobj.file)
console.log(fileobj, param)
return request({
method: 'post',
url: '/management/hospital/uploadHos',
headers: { 'Content-Type': 'multipart/form-data' }, // 设置响应头
data: param
})
}
2.导出
/*导出文件流,后端返回为文件*/
/*html*/
<el-button
class="out-item"
type="primary"
icon="el-icon-download"
@click="handleExport"
>导出</el-button>
/*js*/
handleExport() {
exportHospital().then((res) => {
const file = this.$store.state.app.headerContent //文件名从response 的header中获取
const filename = file['content-disposition'].split(';') [1].split('filename=')[1].split('"')[1] // 从content-disposition 中切割出导出文件名称
const en = decodeURIComponent(filename)
const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
if (window.navigator.msSaveOrOpenBlob) {
// 兼容ie
window.navigator.msSaveBlob(blob, en)
} else {
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob) // 创建下载的链接
downloadElement.href = href

downloadElement.download = en // 下载后文件名

document.body.appendChild(downloadElement)
// 此写法兼容火狐
const evt = document.createEvent('MouseEvents')
evt.initEvent('click', false, false)
downloadElement.dispatchEvent(evt)

document.body.removeChild(downloadElement)
}
})
},

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜丶陌颜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值