开发微信小程序应用中有个需求就是客户评价和下工单,这里都会用到上传多张图,在之前写的一篇博客关于微信小程序上传多张图线下测试还可应用但是线上不可以,查找原因是因为线程的原因所以会用到递归的方法解决。
首先在app.js 中定义一个方法
uploadimg:function(data) {
var that = this,
i = data.i ? data.i : 0,
success = data.success ? data.success : 0,
fail = data.fail ? data.fail : 0;
wx.uploadFile({
url: data.url,
filePath: data.path[i],
name: 'logo',
formData:{
id:data.id
},
success: function(res) {
success++;
console.log(res)
console.log(i);
},
fail: function (res) {
fail++;
console.log('fail:' + i + "fail:" + fail);
},
complete: function (res){
console.log(i);
i++;
if (i == data.path.length) { //当图片传完时,停止调用
console.log('执行完毕');
console.log('成功:' + success + " 失败:" + fail);
} else {
console.log(i);
data.i = i;
data.success = success;
data.fail = fail;
that.uploadimg(data);
}
}
})
}
在上传页面中的js文件代码如下
chooseimage: function () {
var _this = this;
wx.chooseImage({
count: 7, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
console.log(res)
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
_this.setData({
tempFilePaths: res.tempFilePaths
})
}
})
},
savePersonInfo:function(e){
console.log(this.data.list)
var pics = this.data.tempFilePaths
var that = this;
var data = e.detail.value
if(data.shenqing==""){
wx.showToast({
title: '请输入申请说明',
icon: 'success',
duration: 2000
})
}else{
console.log(that.data.img);
wx.request({
method: 'POST',
url: 'http://xx/index.php/WxApi/wxOrder ', //仅为示例,并非真实的接口地址
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
data: {
stype: '2',
img: that.data.img,
ocid: that.data.ocid,
username: that.data.list.username,
phone: that.data.list.tel,
ro_address: that.data.list.address,
ptel: that.data.list.ptel,
order_time: that.data.dates,
remark: data.shenqing
},
success: function (res) {
if(res.data.code==1){
app.uploadimg({
id: res.data.data,
url: 'http://xx/index.php/WxApi/wxImg',
path: pics
})
wx.showToast({
title: '提交成功',
icon: 'success',
duration: 2000
})
wx.switchTab({
url: '../mine/mine',
})
}else{
wx.showToast({
title: '网络服务器错误',
icon: 'success',
duration: 2000
})
}
}
})
}
},
服务器端
//微信上传图片
public function wxImg() {
//上传图片
if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
$info = img_upload();
$logo = $info['logo']['savepath'] . $info['logo']['savename'];
$data = array(
'pid' => I('id'),
'logo' => $logo
);
$result = M("admin_order_photo")->add($data);
}
}
//提交微信工单
public function wxOrder() {
if (IS_POST) {
$data = array(
);
//判断是否有工单
if(I("ro_order")){
$data["stype"]=3;
$result = M("admin_receive_order")->where(array("ro_order"=>I("ro_order")))->save($data);
}else{
$result = M("admin_receive_order")->add($data);
}
if ($result) {
exit(json_encode(array('code' => 1, 'msg' => 'success', 'data' => $result)));
} else {
exit(json_encode(array('code' => -2, 'msg' => 'error', 'data' => "提交失败")));
}
}
}