本篇文章为大家展示了利用android进行多图上传时出现失败如何解决,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
微信提供了文件上传的方法wx.uploadFile来上传我们的图片
wx.chooseImage({
success: function(res) {
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'http://example.weixin.qq.com/upload', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData:{
'user': 'test'
},
success: function(res){
var data = res.data
//do something
}
})
}
})
但是针对多图上传微信没有给出相应的方法来解决,如此我们只能消耗我们程序猿的脑细胞来解决了,最开始我使用了for循环来循环上传我的图片,恰好本人是苹果手机所以上传是没有问题的,本以为轻松解决了这个问题但是提交到测试以后坑了。测试MM说他那里提示上传失败。
于是借来测试手机打印出来错误消息
uploadFile:fail:the same task is working
wx.uploadFile不能并行,因为wx.uploadFile是一个异步函数,所以循环的时候在安卓手机上会出现并行
所以上面的通过循环wx.uploadFile方法进行多图上传肯定是不能行的了,既然不能并行我们是不是可以让wx.uploadFile执行完后再执行wx.uploadFile了。看下修改后的代码
这里为上传图片的方法,在里面作出判断上传完成以后重复调用upload_img
var img_index = 0;//上传带第几张
var image_list1 = new Array();
//上传图片
var upload_img = function (that, file_name) {
that.setData({
hidden: false
});
wx.uploadFile({
url: '',
filePath: file_name,
name: 'file',
success: function (res) {
//此处判断是否上传成功
var obj = JSON.parse(res.data);
if (obj.ret_code == 1) {
//上传成功以后将上传成功的图片加入数组显示出来,这样可以避免没有上传成功的图片就不显示
var uploads = new Array();
var image_list = new Array();
//加入返回值
uploads = that.data.upload;
uploads.push(obj.data);
//加入图片
image_list = that.data.tempFilePaths;
image_list.push(file_name);
that.setData({
upload: uploads,
tempFilePaths: image_list
});
//上传成功一次img_index+1,下面再次调用upload_img上传图片就可以直接传image_list1[img_index],也就是下一张图片的链接
img_index = img_index + 1;
//这里需要作出判断图片是否上传完成,如果完成则取消缓冲框hidden
if (img_index < image_list1.length) {
upload_img(that, '' + image_list1[img_index]);
} else {
that.setData({
hidden: true
});
}
//刷新界面
that.update();
} else {
that.setData({
hidden: true
});
utils.show_toast(obj.msg);
}
},
fail: function (res) {
that.setData({
hidden: true
});
utils.show_toast('加入失败');
}
})
}
选择图片方法
if (that.data.tempFilePaths.length < 9) {
wx.chooseImage({
count: 9 - that.data.tempFilePaths.length, // 最多可以选择的图片张数,默认9
sizeType: ['compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
success: function (res) {
// success
img_index = 0;
image_list1=new Array();
//将选择的图片放入要上传的数组中
for (var i = 0; i < res.tempFilePaths.length; i++) {
console.log(i + ';' + res.tempFilePaths[i]);
image_list1.push(res.tempFilePaths[i]);
}
//最开始上传第一张图片
upload_img(that, '' + image_list1[img_index]);
},
fail: function () {
utils.show_toast('选取失败');
}
})
} else {
utils.show_toast('当前最多只能选择9张图片');
}
通过上面的代码就可以完成多图上传了,这样也避免了Android手机报错的漏洞
这里封装了一个错误消息弹窗避免写重复的代码
utils.show_toast(‘当前最多只能选择9张图片')
//弹窗
function show_toast(text) {
wx.showToast({
title: text,
icon: ‘success',
duration: 2000
});
}
上述内容就是利用android进行多图上传时出现失败如何解决,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。