elv*_*eti 2 upload vue.js axios
我正在尝试获取上传进度以显示当前文件的上传进度,以及一次上传多个文件时的总进度。我不能使用 .loaded/.total 的经典方式,因为 onUploadProgress 被不同的异步请求多次调用,所以百分比只会来回跳跃。使用下面的代码,我至少可以显示剩余文件的进度(例如,上传 3 个文件中的 1 个时为 33%),但它没有考虑文件的加载量(因此它保持在 0%直到整个文件都打开,然后它会在一秒钟内跳到 33%)。
requests.push(
axios.post(this.uploadUrl, formData, {
onUploadProgress: progressEvent => {
if (progressEvent.loaded === progressEvent.total) {
this.progress.current++
}
// this.progress.percent = parseInt(Math.round((progressEvent.loaded * 100) / progressEvent.total))
this.progress.percent = parseInt(Math.round((this.progress.current * 100) / this.progress.total))
}
})
)
axios.all(requests)
Run Code Online (Sandbox Code Playgroud)
我的问题是我不知道所有文件的 progressEvent.total 并且我无法区分单个请求。也没有onUploadStart我可以获取总数并求和的地方。谁能帮我解决这个问题?如果您有任何疑问或不清楚的地方,请发表评论(我希望它有点易于理解)
如果有人偶然发现这个问题,我终于用下面的代码修复了它。诀窍是计算每个文件的进度,将其保存到一个对象中(使用文件名作为关键字),然后将进度相加并除以总文件数。
// loop through all files and collect requests
for (let file of files) {
let formData = new FormData()
formData.append(file['name'], file)
requests.push(
axios.post(this.uploadUrl, formData, {
onUploadProgress: progressEvent => {
if (progressEvent.loaded === progressEvent.total) {
this.progress.current++
}
// save the individual file's progress percentage in object
this.fileProgress[file.name] = progressEvent.loaded * 100 / progressEvent.total
// sum up all file progress percentages to calculate the overall progress
let totalPercent = this.fileProgress ? Object.values(this.fileProgress).reduce((sum, num) => sum + num, 0) : 0
// divide the total percentage by the number of files
this.progress.percent = parseInt(Math.round(totalPercent / this.progress.total))
}
})
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2292 次 |
| 最近记录: |