最近写的一个公众号项目中遇到一个功能,用到了微信的api 调用相册选择图片,上传回显,之前的写法如下
wx.chooseImage({
count: 5, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
console.log(res);
const localIds = res.localIds
console.log(that.imgArray, 88);
// wkwebview的情况下需要使用getLocalImgData
for (let i = 0; i < localIds.length; i++) {
console.log(1, 2);
wx.getLocalImgData({
localId: localIds[i],
success: (res2) => {
let localData = res2.localData // localData是图片的base64数据,可以用img标签显示
// localData = localData.replace('jgp', 'jpeg') // iOS 系统里面得到的数据,类型为 image/jgp,因此需要替换一下
// console.log(localData)
if (localData.indexOf('data:image') == 0) {
that.imgArray.push(localData);
that.imageBlob.push(localData);
} else {
that.imgArray.push("data:image/jpeg;base64," + localData.replace(/\n/g, ""));
that.imageBlob.push("data:image/jpeg;base64," + localData.replace(/\n/g, ""));
}
// that.handlingImg -= 1;
console.log(that.imgArray, 99);
}
})
}
}
})
经过测试之后发现,上传一张图片没问题,选择多张的时候,getLocalImgData在循环中未执行回调方法,改了多次才发现,循环中只会执行一次,改成promise 执行,完美解决
wx.chooseImage({
count: 5, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function(res) {
console.log(res);
const localIds = res.localIds
that.readImages(localIds);
console.log(that.imgArray, 88);
}
}),
async readImages(localIds) {
console.log(localIds.length, '长度');
for (let i = 0; i < localIds.length; i++) {
console.log('循环' + i + 1);
await this.doreadImage(localIds[i]);
}
},
doreadImage(item) {
let that = this;
return new Promise(resolve => {
wx.getLocalImgData({
localId: item,
success: function(res2) {
let localData = res2.localData // localData是图片的base64数据,可以用img标签显示
if (localData.indexOf('data:image') == 0) {
that.imgArray.push(localData);
that.imageBlob.push(localData);
} else {
that.imgArray.push("data:image/jpeg;base64," + localData.replace(/\n/g, ""));
that.imageBlob.push("data:image/jpeg;base64," + localData.replace(/\n/g, ""));
}
resolve()
// that.handlingImg -= 1;
console.log(that.imgArray, 99);
},
fail: function(err) {
window.console.error(err);
}
});
});
}