- uniapp实现图片视频批量上传
- 一般这种批量上传 后端处理会比较好 目前此文章 只展示前端实现 前端需要循坏调用上传的接口 一般也不建议前端批量的去调用这个接口 会对网络资源造成较大压力,甚至可能导致浏览器或服务器出现性能问题。如果服务器端对并发请求有限制,这种方式可能会导致部分请求失败。
核心代码 如下
fileUpdate() {
console.log('开始上传,videoList:', this.videoList);
console.log('开始上传,imageList:', this.imageList);
uni.showLoading({
mask: true,
title: "上传中..."
});
let _this = this;
let filePaths = this.videoList.concat(this.imageList);
console.log("filePaths-----------", filePaths);
if (filePaths.length === 0) {
uni.showToast({
icon: "none",
title: "暂无需要上传的"
});
return;
}
let uploadNum = filePaths.length;
let api = AppConfig.SERVICE_URL + "你的后端接口";
// 定义一个递归函数来依次上传文件
function uploadNext(index) {
if (index >= filePaths.length) {
uni.hideLoading();
if (_this.videoList.length > 0 || _this.imageList.length > 0) {
console.log('未上传成功的视频列表:', _this.videoList);
console.log('未上传成功的图片列表:', _this.imageList);
// uni.showToast({
// title: "部分影像未上传成功,请再次保存!",
// icon: "none",
// });
this.videoList=[]
this.imageList=[]
} else {
uni.showToast({
title: "上传完成!",
icon: "none",
});
}
return;
}
let item = filePaths[index];
item.fileName = _this.getFileName(item.tempFilePath);
console.log("filePaths22222222", item.fileName);
let formData = {
token: "",
channelCode: "xcx",
objectNo: _this.businessNumber,
objectType: "xxxx",
objectName: "xxxxx",
queryTime: _this.reportDate,
itemno: "2901",
longitude: _this.longitude,
latitude: _this.latitude,
address: _this.address,
fileName: item.fileName,
Method: 'upload',
Action: 'upload'
};
uni.uploadFile({
url: api,
filePath: item.tempFilePath,
name: 'file',
formData: formData,
success: (res) => {
try {
res.data = JSON.parse(res.data);
if (res.data.result === 'SUCCESS') {
_this.removeSuccessFile(res.data.fileName);
_this.$forceUpdate(); // 强制更新组件
}
} catch (e) {
// 处理解析异常
}
},
fail: (err) => {
console.log("err", err);
uni.showToast({
title: err.errMsg,
icon: "none"
});
},
complete: () => {
uploadNext(index + 1);
}
});
}
// 开始上传第一个文件
uploadNext(0);
},
这里就结束啦
扩展一下: 前端批量实现单个接口的调用 比如 全选 取消购物车
batchCancelCart() {
// 从this.dataList[2]中筛选出被选中的商品项(selected为true的项)
const selectedItems = this.dataList[2].filter(item => item.selected);
// 如果没有选中的商品项,直接返回,不进行后续操作
if (selectedItems.length === 0) {
return;
}
// 弹出确认对话框,询问用户是否确认批量取消商品的购物车
this.$confirm('是否确认批量取消商品的购物车?', '提示', {
confirmButtonText: '确认',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 对于每个被选中的商品项,创建一个删除请求的Promise数组
const requests = selectedItems.map(item => {
return this.$api.deleteFavorite({
id: item.favoriteId
}).then(res => {
// 如果请求成功(status_code为1)
if (res.status_code === 1) {
// 找到该商品项在this.dataList[2]中的索引
const index = this.dataList[2].findIndex(i => i.id === item.id);
// 如果索引存在(大于 -1),从this.dataList[2]中删除该商品项
if (index > -1) {
this.dataList[2].splice(index, 1);
}
// 返回请求结果
return res;
} else {
// 如果请求失败,返回一个被拒绝的Promise,携带错误信息
return Promise.reject(res.msg);
}
}).catch(error => {
// 捕获请求过程中的错误,返回一个被拒绝的Promise,携带错误信息
return Promise.reject(error);
});
});
// 并行执行所有请求,并等待所有请求完成(无论成功或失败)
Promise.allSettled(requests).then(results => {
// 统计成功的请求数量
const successCount = results.filter(result => result.status === 'fulfilled').length;
// 统计失败的请求数量
const failedCount = results.filter(result => result.status === 'rejected').length;
// 如果有成功的请求,显示成功消息
if (successCount > 0) {
this.$message({
message: `成功取消 ${successCount} 项商品的购物车`,
type: 'success'
});
}
// 如果有失败的请求,拼接错误信息并显示错误消息
if (failedCount > 0) {
const errorMessages = results
.filter(result => result.status === 'rejected')
.map(result => result.reason)
.join(';');
this.$message.error(`部分取消失败:${errorMessages}`);
}
// 更新全选状态,判断是否所有商品项都被选中
this.isAllSelected = this.dataList[2].length > 0 && this.dataList[2].every(item => item.selected);
});
}).catch(() => {
// 用户取消操作时执行的代码,这里没有具体逻辑,仅作为占位
});
},