本篇博文主要記錄我們在寫項目的時候經常需要用到導入和導出。
導入
- 首先定義一個模態彈窗,一般情況下會使用一個
input
(設置opacity:0)覆蓋在顯示的按鈕上面
<!-- 3.導入 -->
<Modal title="批量導入" v-model="importVisual" width="450px" class="page-open-question-import">
<div class="import-btn">
<input
class="upload-input"
@change="fileChange($event)"
name="files"
type="file"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
/>
<Button
type="primary"
ghost
style="margin-left:40px"
icon="ios-cloud-upload-outline"
>點擊上傳Excel文件</Button>
<span class="file-name" v-show="fileName" :title="fileName">{{fileName}}</span>
</div>
<div class="import-text">
<span>文件小於10M,內容需符合模板規范</span>
<span>導入文檔前請先添加好相應的類目</span>
</div>
<div class="import-example" @click="download">
<Icon type="ios-cloud-download-outline" />下載規范模板
</div>
<div slot="footer">
<Button @click="importVisual=false">取消</Button>
<Button type="primary" @click="importOk">確定</Button>
</div>
</Modal>
- 通過
type='file'
的輸入框獲取到文件信息,一般情況下的導入接口使用的是formdata
信息
// 導入選擇文件
fileChange (el) {
this.importFile = el.target.files[0];
this.fileName = this.importFile.name;
},
// 確定導入
importOk () {
let param = new FormData();
param.append('file', this.importFile);
importData(param, {
kgId: this.kgId
}).then(res => {
// 導入成功后操作
......
this.importVisual = false;
this.$Message.success('導入成功!')
})
},
導出
get 請求
一般情況下,我們可以直接使用window.open()
的方法來導出后端提供的get請求;
// 根據參數導出數據
downloadModel () {
window.open(
`${httpConfig.baseURL}/kg/dataset/data/template/${this.datasetId}`
);
}
post 請求
有的接口因為傳參比較多,會需要使用post請求,那么上面的方法就不合適,通用的請求會出現亂碼,大多數情況下我們會使用表單提交的方法
- 創建form表單請求的方法
// 導出文件
formSubmit (param, url) {
var $form = document.getElementById('exportForm');
if (!$form) {
$form = document.createElement('form');
$form.setAttribute('id', 'exportForm');
$form.setAttribute('method', 'post');
$form.style.display = 'none';
document.getElementById('exportParent').appendChild($form);
}
$form.setAttribute('action', url);
// 記得要把token信息帶上
let token = this.$cookies.get('access_token');
param.access_token = token;
for (var obj in param) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = obj;
input.value = param[obj];
$form.appendChild(input);
}
$form.submit();
}
- 導出的方法中使用
// 確認導出
exportOk () {
// 根據label獲取id
......
// 請求導出
this.formSubmit(
{
kgId: this.kgId,
status: this.status,
categoryIds: this.categoryIds.join('|')
},
this.exportUrl
);
}