uniapp队列下载
uniapp 队列下载实现方法
在 uniapp 中实现队列下载功能,可以通过以下方法进行:
方法一:使用 Promise 和递归实现
创建一个下载队列数组,通过递归方式逐个下载文件。

let downloadQueue = []; // 存储下载任务
let currentDownload = null; // 当前下载任务
function addToQueue(url) {
downloadQueue.push(url);
if (!currentDownload) {
startDownload();
}
}
function startDownload() {
if (downloadQueue.length === 0) {
currentDownload = null;
return;
}
const url = downloadQueue.shift();
currentDownload = uni.downloadFile({
url: url,
success: (res) => {
if (res.statusCode === 200) {
console.log('下载成功:', res.tempFilePath);
}
startDownload();
},
fail: (err) => {
console.error('下载失败:', err);
startDownload();
}
});
}
方法二:使用 async/await 实现
利用 async/await 语法可以更清晰地控制下载流程。

const downloadQueue = [];
let isDownloading = false;
async function processQueue() {
if (isDownloading || downloadQueue.length === 0) return;
isDownloading = true;
const url = downloadQueue.shift();
try {
const res = await uni.downloadFile({ url });
if (res[0].statusCode === 200) {
console.log('下载成功:', res[0].tempFilePath);
}
} catch (err) {
console.error('下载失败:', err);
} finally {
isDownloading = false;
processQueue();
}
}
function addToQueue(url) {
downloadQueue.push(url);
processQueue();
}
方法三:限制并发数的队列下载
如果需要控制同时下载的数量,可以扩展方法二。
const MAX_CONCURRENT = 3; // 最大并发数
const downloadQueue = [];
let activeDownloads = 0;
async function downloadFile(url) {
activeDownloads++;
try {
const res = await uni.downloadFile({ url });
if (res[0].statusCode === 200) {
console.log('下载成功:', res[0].tempFilePath);
}
} catch (err) {
console.error('下载失败:', err);
} finally {
activeDownloads--;
processQueue();
}
}
function processQueue() {
while (downloadQueue.length > 0 && activeDownloads < MAX_CONCURRENT) {
const url = downloadQueue.shift();
downloadFile(url);
}
}
function addToQueue(url) {
downloadQueue.push(url);
processQueue();
}
注意事项
- 网络请求需要在 manifest.json 中配置合法域名
- 大量文件下载时注意内存管理
- 考虑添加失败重试机制
- 进度反馈可以通过 uni.onDownloadProgress 实现
扩展功能
可以进一步完善队列下载功能:
// 添加任务优先级
function addToQueue(url, priority = false) {
if (priority) {
downloadQueue.unshift(url); // 插入队列头部
} else {
downloadQueue.push(url); // 插入队列尾部
}
processQueue();
}
// 添加下载进度监控
uni.onDownloadProgress((res) => {
console.log('下载进度:', res.progress);
});
以上方法可以根据实际需求进行调整,实现适合项目的队列下载功能。






