最近写项目碰到一个新需求,文件上传需要分步进行。这里使用的antd组件库的对话框结合表格组件实现。
效果如下:
实现思路:
先写一个type为file的input,在input上绑定一个ref为upload,最后将其宽高设置为0(也就是将其隐藏),在写一个button,在其点击事件中通过this.$refs.upload.click()拿到input。
实现代码
<a-modal v-model="isShow" title="请上传数据文件" :footer="null" @ok="handleOk">
<div>
<p-button @click="showFileSystem">上传附件</p-button>
<span style="padding: 10px">支持批量上传,格式为EXCEL、WORD文件</span>
<!-- style="width:0;height:0;" -->
<input type="file" ref="upload" multiple
accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.excel"
style="width: 0; height: 0" @change="onFileChange" />
</div>
<a-table size="middle" style="padding-top: 20px; width: 400px" :locale="{emptyText:'请点击 上传附件 进行文件上传'}"
rowKey="id" :columns="columns" :data-source="endList" :pagination="false" :customRow="tabClick">
<template slot="status" slot-scope="text, rows">
<a-icon v-show="rows.status == 0" type="history" />
<a-icon v-show="rows.status == 1" type="loading" />
<a-icon v-show="rows.status == 2" type="check-circle" theme="twoTone" two-tone-color="#52c41a" />
<!-- <a-icon type="history" /> -->
<span class="yuanStatus" style="padding: 10px">{{ fileStatus(rows.status) }}</span>
</template>
<a @click="deleteList" slot="delete" style="color: #ff3b30">删除</a>
</a-table>
<div class="uploadBtn">
<p-button class="upload1" type="default" @click="handleOk">取消</p-button>
<p-button type="primary" :disabled="endList.length === 0" style="margin-top: 16px"
@click="handleUpload"> 开始上传 </p-button>
</div>
</a-modal>
js代码
handleUpload() {
console.log(this.endList)
this.endList.forEach(item => {
if(item.status<2){
item.status = 1
}
})
uploadProjection(this.$route.query.id, this.fileList).then((res) => {
this.fileList = []
this.endList.forEach(item => {
item.status = 2
})
this.$nextTick(() => {
getUploadList(this.$route.query.id, 1).then(res => {
console.log(res)
this.newArr = res
})
})
setTimeout(() => {
this.$message.success('文件上传成功')
},500)
})
},
showFileSystem() {
this.$refs.upload.click()
},
deleteList() {
console.log(this.endList)
this.endList.splice(this.delId, 1)
},
onFileChange(e) {
console.log(e.target.files)
this.newFileList = Array.from(e.target.files)
console.log(this.newFileList)
// this.newFileList = JSON.parse(JSON.stringify(e.target.files))
// this.newFileList = [].slice.call(this.newFileList)
let arr = []
let obj = {}
// 表格
Array.from(e.target.files).forEach((item, index) => {
obj = {
fileName: item.name,
status: 0,
size: item.size,
}
arr.push(obj)
})
console.log(arr)
this.endList = [...this.endList, ...arr]
// 上传
this.fileList = [...this.fileList, ...this.newFileList]
console.log(this.fileList)
this.fileList.forEach((item, index) => {
item.fileName = item.name
item.status = 0
})
},