window.worker.onmessage = ({ data }) => {
const promiseList = []
this.chunckList.forEach((item, index) => {
promiseList.push(new Promise((resolve, reject) => {
this.$axios.post(‘/chunckAlready‘, { name: data.hash, hash: `${data.hash}-${index}` }).then(res => {
if (res.data.already === false) { // 后端不存在该切片,上传切片
const formData = new FormData()
formData.append(‘hash‘, `${data.hash}-${index}`)
formData.append(‘name‘, `${data.hash}`)
formData.append(this.fileName, item.file)
this.$upload.post(this.baseUrl, formData, {
onUploadProgress: progressEvent => {
this.chunckList[index].percent = (progressEvent.loaded / progressEvent.total * 100 | 0)
}
}).then(res => { resolve(res) })
} else {
this.chunckList[index].percent = 100
resolve()
}
})
}))
})
Promise.all(promiseList).then(() => { // 全部切片上传完毕,通知后端合并切片
this.$axios.post(‘/merge‘, { hash: data.hash, fileName: `${data.hash}-${this.file.name}` }).then((res) => {
this.$emit(‘finish‘, res.data)
if (this.fileList.length) { // 如果选中多个文件,重复切片、上传操作
this.file = this.fileList[0]
this.chunckList = this.createChunkList(this.fileList.shift())
window.worker.postMessage(this.chunckList)
} else {
this.showPercent = false
this.$nextTick(() => {
this.chunckList = []
window.worker.terminate()
})
}
})
})
}