我遇到了一个问题,希望有人能帮助我。 我需要用axios实现文件分块上传,需要一个个分块发送到我的服务器。所以新的 axios 请求应该在前一个请求完成之后发生。 现在,请求没有按顺序发送。 我的代码如下:
addChunk(file) { // I receive file from my file uploader
this.getBase64(file[0].file).then((base64) => {
this.convertChunks = base64.replace(base64.substring(0, base64.search(',') + 1), '')
this.convertedArr = this.convertChunks .match(/.{1,500000}/g) //here I convert it into base64 with helper function
})
for (let i in this.convertedArr) {
if (this.uploadSuccess === false) return null
axios({
url: `${domain}`,
method: 'POST',
data: [this.convertedArr[i]]
})
.then(() => {
if (parseInt(i) === this.convertedArr.length - 1) {
this.nextFunction() //after the last chunk is sent successfully, i need to call another function
}
})
.catch((error) => {
console.log(error)
})
}
},
最佳答案
使用 async/await
语法使您的方法可以等待 axios
请求完成。
同时切换到 for...of
而不是 for...in
。后者用于循环遍历对象的可枚举属性,尽管它可用于数组,但在顺序很重要时应避免使用。
通过遍历 this.convertedArr.entries()
展开 for...of
。这将为数组中的每个项目创建一个包含 [ index, value ]
的数组,因此您可以使用索引。
使用 try...catch...finally
,您可以捕获等待的函数调用可能产生的任何错误。 finally
部分用于确保在请求成功或失败时调用该部分。
async addChunk(file) { // I receive file from my file uploader
this.getBase64(file[0].file).then((base64) => {
this.convertChunks = base64.replace(base64.substring(0, base64.search(',') + 1), '')
this.convertedArr = this.convertChunks.match(/.{1,500000}/g) //here I convert it into base64 with helper function
})
for (const [ i, item ] of this.convertedArr.entries()) {
if (this.uploadSuccess === false) return null
try {
await axios({
url: `${domain}`,
method: 'POST',
data: [item]
});
} catch(error) {
console.log(error)
} finally {
if (parseInt(i) === this.convertedArr.length - 1) {
this.nextFunction();
}
}
}
}
关于javascript - 使用axios上传 block 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64990763/