VUE+VANT 实现文件上传读取及下载功能
项目中要实现的效果
1、页面布局
<p class="download" @click="downloadExcel">下载导入模板</p> <div class="uploader-box"> <van-uploader v-model="fileList" accept=".xls, .xlsx" :after-read="afterRead" :deletable="false" @delete="delFile" multiple> <van-icon name="plus" /> </van-uploader> </div>
2、VUE方法代码
// 下载excel downloadExcel() { templateDownLoad().then(res => { // var fileName = res.headers("Content-Disposition").split(";")[1].split("filename=")[1]; // var fileNameUnicode = res.headers("Content-Disposition").split("filename*=")[1]; // if (fileNameUnicode) {// filename* 时,取filename* 并进行解码 // fileName = decodeURIComponent(fileNameUnicode.split("''")[1]); // } let blob = new Blob([res], { type: 'application/vnd.ms-excel' }) if ('msSaveOrOpenBlob' in navigator) { // IE导出 window.navigator.msSaveOrOpenBlob(blob, fileName); } const link = document.createElement('a') link.style.display = 'none' link.href = URL.createObjectURL(blob) link.download = '雇主团单投保信息导入模版' //下载的文件名 document.body.appendChild(link) link.click() document.body.removeChild(link) }).catch(error => { this.$toast("下载失败,请稍后重试!") }) },
//上传文件 afterRead(file) { let _this = this const formData = new FormData(); formData.append('file', file.file) excelUpload(formData).then(res => { if (res.code == '0') { // 文件上传成功 this.$toast("文件上传成功!") this.employerObj.empOrderInfo = res.result this.submitFlag = false } else if(res.code == '001') { // 下载错误信息 setTimeout(function(){ _this.errorFlag = true _this.fileNo = res.result.contractNo },1000) } else if(res.code == '110001') { // 直接提示错误信息 this.$toast(res.message) } }).catch(error => { console.log(error) }) },
3、配置接口请求方式,responseType: bolb
/** * 模板下载 * **/ export function templateDownLoad(){ return http.get(`${URI.augeas}/geek/emp/templateDownLoad`,{responseType:'blob'}) }
如有问题,欢迎大家指正
认真做事儿,踏实做人
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?