基於el-upload組件實現上傳下載excel文件
在vue項目中,使用了element組件,要基於其中的下載組件el-upload實現上傳和下載excel的功能,發現element官網上的說明說的很不清楚,找了很多資料和實踐後,總結了以下的用法。
element官網中el-upload: el-upload
說明
主要實現兩部分,一是上傳文件,基於el-upload;二是下載文件,這個根據具體項目要求,這裏只介紹後端返回下載鏈接,前端打開下載鏈接直接進行頁面下載
一、el-upload實現上傳
話不多說先上代碼
<el-upload
v-loading="uploadLoading"
:multiple='false'
:auto-upload='true'
:before-upload="beforeUpload"
:action="$newApiLocation + '/question/importQuestionExcel'"
:limit="1"
:on-exceed="handleExceed"
:http-request="uploadExcel"
:file-list="fileExcelList">
<el-tooltip class="item" effect="dark" content="請根據模板批量上傳題目!" placement="top">
<el-button><i class="el-icon-upload2"></i>批量上傳</el-button>
</el-tooltip>
</el-upload>
這裏主要涉及的點都是在el-upload上的設置
1.handleExeed方法爲文件數量超過limit時觸發的方法
// 上傳文件個數超過定義的數量
handleExceed (files, fileList) {
this.$message.warning('當前限制選擇 1 個文件,請刪除後繼續上傳');
},
2.file-list爲上傳的文件所存儲的字段,不需要可以隱藏
3.auto-upload爲選擇文件自動上傳
4.beforeUpload爲文件上傳前調用的方法,即調取接口傳數據前,對數據的處理
// 上傳文件之前的鉤子
beforeUpload (file) {
const isText = file.type === 'application/vnd.ms-excel';
const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
if (!isText && !isTextComputer) {
this.$message.warning('請上傳excel格式文件!');
};
return (isText || isTextComputer);
},
這裏限制了上傳文件類型爲excel文件,如有需要可以設置文件的大小等等
5.http-request綁定的方法是真正處理文件上傳的方法,在此調用接口,錯誤處理等等
// 提交批量上傳題目的excel表格
uploadExcel (item) {
this.uploadLoading = true;
const fileObj = item.file;
const form = new FormData();
form.append('file', fileObj);
form.append('surveyId', this.$route.params.surveyId);
this.importQuestionExcel(form).then(res => {
this.$message.success('文件:' + fileObj.name + '上傳成功,題目批量添加完成!');
// 上傳成功後,重新獲取問題列表,並清空excel列表,可繼續上傳
this.getSurveyQuestion(this.$route.params).then(() => {
this.fileExcelList = [];
}).finally(() => {
this.fileExcelList = [];
});
}).catch(() => {
// this.$message.error('文件:' + fileObj.name + '上傳失敗!');
}).finally(() => {
this.fileExcelList = [];
this.uploadLoading = false;
});
},
其中,this.importQuestionExcel()爲綁定的post接口,注意這裏的:action也要將此接口地址綁定。
由此,便可將數據傳遞到後端
二、基於a鏈接實現打開下載鏈接防抖
需要下載文件時,如果數據存在數據庫,通過後端返回的下載地址,直接打開進行下載。有如下方式:
1、直接使用window.open()打開鏈接
頁面會出現抖動
2、利用a鏈接的href屬性,打開鏈接
流程是:直接用js創建一個隱藏的a鏈接,將後端返回的下載鏈接賦給href,觸發a鏈接click事件,實現文件下載,然後刪除a鏈接。整個過程不會看到a鏈接,而且頁面不會抖動
this.downloadExcel(params).then(res => {
const url = res;
// window.open(url);
// 創建a標籤下載返回的下載地址
const elink = document.createElement('a'); // 創建a標籤
elink.style.display = 'none';
elink.href = url;
document.body.appendChild(elink);
elink.click(); // 觸發點擊a標籤事件
document.body.removeChild(elink);
});