<template>
<a-modal
title="批量导入"
width="600px"
:visible="visible"
@cancel="handleCancel"
>
<div>
<div>
<label>文件模板:</label>
<a-button type="primary" @click="download" icon="download"> 下载模板 </a-button>
</div>
<br />
<div>
<label>上传文件:</label>
<a-upload
name="file"
:multiple="false"
:fileList="fileList"
:remove="handleRemove"
:beforeUpload="beforeUpload"
>
<a-button> <a-icon type="upload" /> 选择文件 </a-button>
</a-upload>
</div>
</div>
<template slot="footer">
<a-button @click="handleCancel">关闭</a-button>
<a-button type="primary" @click="handleImport" :disabled="fileList.length === 0" :loading="uploading">
{{ uploading ? '上传中...' : '开始上传' }}
</a-button>
</template>
</a-modal>
</template>
<script>
import Vue from 'vue'
// 上传组件 header 需要存入 token
import { ACCESS_TOKEN } from '@/comment/index'
export default {
data() {
return {
headers: null,
visible: false,
fileList: [],
down: '下载模板接口',
upload: '导入接口',
uploading: false,
}
},
created() {
const token = Vue.ls.get(ACCESS_TOKEN)
this.headers = { 'X-Access-Token': token }
},
methods: {
show(name) {
this.uploading = false
this.visible = true
this.fileList = []
},
download() {
window.open(this.down)
},
handleCancel() {
this.visible = false
},
// 移除文件
handleRemove(file) {
const index = this.fileList.indexOf(file)
const newFileList = this.fileList.slice()
newFileList.splice(index, 1)
this.fileList = newFileList
},
beforeUpload(file) {
// 保持文件数组中只能存储一个文件
this.fileList = [file]
return false
},
// 只有点击上传按钮,才能发送接口
handleImport() {
const { fileList } = this
const formData = new FormData()
fileList.forEach((file) => formData.append('file', file) })
this.uploading = true
this.$post(this.upload, formData).then((res) => {
this.uploading = false
if (res.success) {
this.visible = false
this.$message.success('导入上传成功')
} else {
this.$message.warning('导入上传失败')
}
})
},
},
}
</script>
完整效果