1. 上傳 EXCEL
Upload組件 點擊跳轉到該組件官方文檔
用到的upload組件參數
參數 | 說明 | 類型 | 可選 | 默認值 |
---|---|---|---|---|
action |
必選 參數,上傳的地址 |
string | --- | --- |
file-list | 上傳的文件列表 | array | --- | [] |
accept | 接受上傳的文件類型 | string | --- | --- |
http-request | 覆蓋默認的上傳行爲 | function | --- | --- |
limit | 最大允許上傳個數 | number | --- | --- |
on-exceed | 文件超出個數限制時的鉤子 | function(files, fileList) | --- | --- |
組件代碼
html
<el-upload
style="display: inline; margin-left: 10px;margin-right: 10px;"
action=""
:http-request="uploadFile"
:limit=1
:on-exceed="fileExceed"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
:file-list="uploadList"
ref="fileupload">
</el-upload>
--說明--
style: 按項目需要添加,請按需保留
action:必需,自定義上傳直接給空串;非自定義,將地址賦給action配合屬性headers、on-success、on-error等
http-request:自定義方法,根據請求的響應手動實現on-success、on-error
file-list:本項目有清空需要【代碼略】
ref:該上傳組件放置dialog中,本項目有置空需求【代碼略】,請按需保留
js
import HTTP_API from '@/httpApi' // 封裝好的axios:get post請求(含headers和攔截器等【代碼略】)
// methods
fileExceed () {
this.$message.error('別貪心!一次只能上傳一個哦~');
},
// 請求成功
importSuccess (res) {
// 後端的返回碼--上傳成功
if (res.code == xxxxx) {
// 顯示√圖標
let e = document.getElementsByClassName('el-upload-list__item-status-label');
e[0].setAttribute('style', 'display:block !important')
// 成功提示
this.$message.success('上傳成功');
// 重新調用列表請求(代碼略)
this.getList();
// 後端的返回碼--上傳失敗
} else {
// 隱藏√圖標
let e = document.getElementsByClassName('el-upload-list__item-status-label');
e[0].setAttribute('style', 'display:none !important')
// 失敗提示--及後端返回的失敗詳情
this.$message.error({
dangerouslyUseHTMLString: true,
duration: 4500,
message: res.remark+',<br/>請刪除上傳失敗的文件,修改後重新上傳'
});
}
},
// 請求失敗
importError (err) {
this.$message.error({
dangerouslyUseHTMLString: true,
duration: 4500,
message: '上傳出現異常,請稍後重試'+',<br/><br/>異常原因:'+err
});
},
// 自定義上傳
uploadFile (item) {
const form = new FormData()
form.append('file', item.file)
HTTP_API.xlsx_upload(form).then(res => {
this.importSuccess(res)
}).catch(err => {
this.importError(err)
})
}
2. 下載 EXCEL
button組件
組件代碼
html
<el-button type="primary" @click="downTemplate" round>下載模板</el-button>
js
import axios from 'axios'
// methods
// 導出模板
downTemplate () {
axios({
method: 'get',
url:'xxx相對地址xxx',
responseType: 'blob'
}).then(res => this.downloads(res.data, res.headers.filename))
},
// 創建模板下載鏈接
downloads (data, name){
if(!data){
return
}
let url = window.URL.createObjectURL(new Blob([data]))
let link = document.createElement('a')
link.style.display ='none'
link.href = url
link.setAttribute('download', `前端拼接後端返回的名字${name}.xlsx`)
document.body.appendChild(link)
link.click()
},
3. 結束語
- 上傳action必須有,空串也好,隨便寫點也行,反正得有
- element的提示允許html代碼,但是要設置dangerouslyUseHTMLString爲true
- 上傳的請求成功(狀態碼200)不等於上傳成功,element的√圖標,需要用js實現顯示隱藏
- 下載時文件名稱爲動態時,請求後端協助在響應的頭部增加filename字段(filename字段中含文字會有問題,後端給我日期數字,相同的文字部分前端拼接)