uniapp如何获取和控制下载进度字段
在uniapp中,如何获取和控制文件下载的进度信息?比如使用uni.downloadFile时,怎样才能实时监控下载进度百分比,并在页面上展示进度条?官方文档提到的progress回调具体如何使用?
2 回复
在uniapp中,使用uni.downloadFile下载文件时,可通过onProgressUpdate回调获取下载进度。示例:
uni.downloadFile({
url: '文件地址',
success: (res) => {},
fail: (err) => {},
onProgressUpdate: (res) => {
console.log('进度:' + res.progress + '%')
}
})
进度信息在res.progress中,范围0-100。
在 UniApp 中,获取和控制下载进度主要通过 uni.downloadFile API 实现,该 API 支持监听下载进度。以下是具体方法:
1. 使用 uni.downloadFile 下载文件
调用 uni.downloadFile 并监听 onProgressUpdate 回调来获取下载进度。
示例代码:
const downloadTask = uni.downloadFile({
url: 'https://example.com/file.zip', // 替换为实际文件 URL
success: (res) => {
if (res.statusCode === 200) {
console.log('下载成功,临时路径:', res.tempFilePath);
}
},
fail: (err) => {
console.error('下载失败:', err);
}
});
// 监听下载进度
downloadTask.onProgressUpdate((res) => {
console.log('下载进度:', res.progress); // 进度百分比(0-100)
console.log('已下载数据长度:', res.totalBytesWritten);
console.log('总数据长度:', res.totalBytesExpectedToWrite);
// 可在此更新 UI 进度条
// this.progress = res.progress; // 例如在 Vue 中绑定到 data
});
2. 控制下载任务
- 暂停下载:
downloadTask.abort(); // 中止下载任务 - 重新开始:需重新调用
uni.downloadFile。
3. 注意事项
- 进度频率:进度回调触发频率由系统决定,通常每 200ms 一次。
- 临时文件:下载的文件为临时路径,需通过
uni.saveFile保存到本地。 - 网络权限:确保
manifest.json中配置了网络请求权限。
4. 完整示例(Vue 页面)
export default {
data() {
return {
progress: 0
};
},
methods: {
startDownload() {
const task = uni.downloadFile({
url: 'https://example.com/file.zip',
success: (res) => {
uni.saveFile({ // 保存到本地
tempFilePath: res.tempFilePath,
success: (saveRes) => {
console.log('文件已保存:', saveRes.savedFilePath);
}
});
}
});
task.onProgressUpdate((res) => {
this.progress = res.progress; // 更新进度条数据
});
},
cancelDownload() {
if (downloadTask) downloadTask.abort();
}
}
};
通过以上方法,即可实时获取下载进度并控制任务中断。

