uniapp断点下载
断点下载实现原理
断点下载的核心是通过HTTP请求头Range字段指定下载范围,服务器返回对应文件片段。客户端需记录已下载的字节位置,中断后从断点位置继续请求。
基本步骤
配置manifest.json
在manifest.json中启用网络下载权限:
{
"networkTimeout": {
"downloadFile": 60000
},
"uni-app": {
"downloadFile": true
}
}
核心代码实现
- 初始化下载任务并记录进度:
let downloadTask = uni.downloadFile({ url: 'https://example.com/largefile.zip', header: { 'Range': 'bytes=' + alreadyDownloaded + '-' }, success: (res) => { if (res.statusCode === 206) { // 处理分片数据 } } });
// 监听进度 downloadTask.onProgressUpdate((res) => { console.log('下载进度:', res.progress); console.log('已下载:', res.totalBytesWritten); });
2. 存储断点信息
使用`uni.setStorageSync`保存已下载字节数:
```javascript
uni.setStorageSync('downloadedBytes', res.totalBytesWritten);
- 恢复下载时读取断点
const alreadyDownloaded = uni.getStorageSync('downloadedBytes') || 0;
注意事项
- 服务器需支持
Range请求,否则返回状态码200而非206。 - 大文件下载建议分片处理(如每10MB一个分片),减少内存压力。
- 安卓平台需检查文件存储权限,iOS需确保沙盒路径可写。
错误处理
- 网络中断时自动重试:
let retryCount = 0; const maxRetry = 3;
function downloadWithRetry() { downloadTask.abort(); if (retryCount < maxRetry) { retryCount++; setTimeout(downloadWithRetry, 2000); } }
- 捕获异常并记录日志:
```javascript
uni.downloadFile({
fail: (err) => {
console.error('下载失败:', err);
uni.reportAnalytics('download_error', { url: err.url });
}
});
完整示例
// 初始化下载
function startDownload() {
const savedBytes = uni.getStorageSync('file_downloaded_bytes') || 0;
const task = uni.downloadFile({
url: 'https://example.com/file.mp4',
header: { 'Range': `bytes=${savedBytes}-` },
success: (res) => {
if (res.statusCode === 206) {
uni.saveFile({
tempFilePath: res.tempFilePath,
success: (saveRes) => {
uni.removeStorageSync('file_downloaded_bytes');
}
});
}
}
});
task.onProgressUpdate((res) => {
uni.setStorageSync('file_downloaded_bytes', res.totalBytesWritten);
});
}






