当遇到大文件上传比如一个Excel里面包含很多个Sheet 遇到大量数据一次性传给后端根本不现实。解决思路:可以把每个Sheet 一个一个上传这样压力就会相对来说小一些了。
这样的话就需要用到循环请求一个接口了,但是请求必须一个一个发送,等上一个成功再请求下一个,就需要考虑异步的问题了。
获取实时上传的进度前端就可以做到:axios
的 onUploadProgress 通过这个事件就可以拿到文件上传的实时进度。
解决异步问题可以使用 async / await**
代码:
async saveExcel() {
this.showbutton = true
this.closebutton = true
const data = this.$refs.luckySheet.getData('草稿')
for (let i = 0; i < data.sheets.length; i++) {
this.progressShow = true
await axios.request({
url: '/api/ManuscriptTemplate/saveSingle', method: 'post', data: this.id ? {
manuscriptId: this.$route.query.id,
templateName: data.info.name,
id: this.id,
sheets: [
{
sheetInfo: JSON.stringify(data.sheets[i]),
sheetName: data.sheets[i].name,
sheetCellData: JSON.stringify(data.sheets[i].celldata),
sheetData: JSON.stringify(data.sheets[i].data),
manuscriptTemplateId: this.id || '00000000-0000-0000-0000-000000000000',
id: data.sheets[i].id || '00000000-0000-0000-0000-000000000000'
}
]
} : {
manuscriptId: this.$route.query.id,
templateName: data.info.name,
sheets: [
{
sheetInfo: JSON.stringify(data.sheets[i]),
sheetName: data.sheets[i].name,
sheetCellData: JSON.stringify(data.sheets[i].celldata),
sheetData: JSON.stringify(data.sheets[i].data),
manuscriptTemplateId: this.id || '00000000-0000-0000-0000-000000000000',
id: data.sheets[i].id || '00000000-0000-0000-0000-000000000000'
}
]
}, onUploadProgress: (progressEvent) => {
var curValue = (progressEvent.loaded / progressEvent.total * 100).toFixed(0)
this.SheetList[i].progress = parseInt(curValue)
}
}).then(res => {
console.log(res)
if (res.data.code === '200') {
this.id = res.data.data
// this.$message.success('保存成功')
this.SheetList[i].state = 1
this.getMenuList()
if (i >= data.sheets.length - 1) {
this.closebutton = false
}
} else {
this.SheetList[i].state = 2
}
})
this.sheetNmu++
}
},
利用onUploadProgress这样就可以实时获取到上传进度 并赋值给 el-progress 进度条
<el-progress v-show="!scope.row.progress<=0"
:percentage="scope.row.progress" />
还存在的问题:1. 如果单个Sheet 过于庞大同样辉报错
2. 一个文件报错后无法继续请求,导致中断