微信小程序踩坑之解决方案记录(长期更新)
上传图片及排序
问题:上传之后的图片未经排序就展示出来了
原始代码:
/**
*
* 多图上传
*/
uploadImage(count = 1) {
return new Promise((resolve, resject) => {
wx.chooseImage({
count,
sizeType: ["compressed"],
sourceType: ["album", "camera"],
success: (res) => {
const tempFilePaths = res.tempFilePaths;
let list = []
let length = []
wx.showLoading({
title: '图片上传中...',
mask: true
})
for (var i = 0; i < tempFilePaths.length; i++) {
wx.uploadFile({
url: ${url},
filePath: tempFilePaths[i],
name: 'file',
async: false
success: res => {
if (res.statusCode == 200) {
const imgSrc = JSON.parse(res.data).body
list.push(imgSrc)
length.push(i)
}
},
complete: function () {
if (length.length == tempFilePaths.length) { //当图片传完时,停止调用
wx.hideLoading()
resolve(list);
}
},
fail: (err => {
wx.hideLoading()
resject(err);
})
})
}
},
fail: err => {
resject(err);
}
})
})
}
目前返回的值:["111.jpg","333.jpg","222.jpg"]
选择多张图片后循环调用后台接口,但是后台返回的图片是无序的,现在要求图片按照选择的顺序展示出来
解决思路:传值后台的时候加上index值,后端返回图片路径以及传给后台的index值,前端根据返回的index值进行排序后输出,规定后台返回的值是"111.jpg,1"
优化后主要代码
const tempFilePaths = res.tempFilePaths;
let list = []; //存放后端返回的值数组
let imgList = [] //前端需要的值数组
let length = [] //判断长度并输出
wx.showLoading({
title: '图片上传中...',
mask: true
})
for (var i = 0; i < tempFilePaths.length; i++) {
wx.uploadFile({
url:${url},
filePath: tempFilePaths[i],
name: 'file',
async: false,
formData: { //前端传值的时候附带index值
'index': i
},
success: res => {
if (res.statusCode == 200) { //后台返回格式:"111.jpg,1"
const img = JSON.parse(res.data).body[0].split(',')[0] //图片路径
const id = JSON.parse(res.data).body[0].split(',')[1] //index值
const imgSrc = {
id,
img
}
list.push(imgSrc) //包含index值得数组
imgList.push(img) //只有图片路径的数组
length.push(i)
}
},
complete: function () {
if (length.length == tempFilePaths.length) { //当图片传完时,停止调用
wx.hideLoading()
for (var i = list.length - 1; i > 0; i--) { //冒泡排序
for (var j = 0; j < i; j++) {
if (list[j].id > list[j + 1].id) {
[imgList[j], imgList[j + 1]] = [imgList[j + 1], imgList[j]];//根据list数组对imgList数组进行排序
}
}
}
resolve(imgList); //输出["111.jpg","222.jpg","333.jpg"]
}
}
}