項目中要實現的效果
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'}) }
如有問題,歡迎大家指正