元素上bindtap方法:(選擇圖檔)
chooseImgHandler: function (e) {
var that = this;
that.count_img = count_img; //允許上傳的圖檔數目
if (that.isGoing) return;
that.isGoing = true;
if (count_img) {
wx.chooseImage({
count: count_img,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
var tempFilePaths = res.tempFilePaths;
wx.showLoading();
that.uploadimg(tempFilePaths);
},
fail: function () {
// App.serverErrorTip("圖檔選擇失敗...");
that.isGoing = false;
}
})
} else {
App.serverErrorTip('已達到上傳圖檔上限啦~');
that.isClicking = false;
}
},
//拿到使用者選擇的圖檔的臨時檔案路徑數組以後,循環上傳到自己的伺服器
//上傳多圖
uploadimg: function (data) {
var that = this,
zero = 0,
i = data.i ? data.i : zero,
success = data.success ? data.success : zero,
fail = data.fail ? data.fail : zero,
count_img = that.count_img;
wx.uploadFile({
url: '自己伺服器的位址',
filePath: data[i],
name: 'file',
formData: {伺服器需要接受的參數},
success: function (resp) {
if (resp.statusCode == 200) {
if (!resp.data || resp.data.indexOf("errcode") != -1) {
var msg = "";
try {
var json = eval("(" + resp.data + ")");
msg = '上傳圖檔失敗:' + json.errmsg;
} catch (e) {
msg = '上傳圖檔失敗'
}
that.wetoast.toast({
title: msg,
duration: 3000
})
fail++;
wx.hideLoading();
} else {
//成功後的回調
//自己的事件方法
that.count_img = count_img;
if (i == (data.length - 1)) {
wx.hideLoading();
}
}
} else {
if (i == (data.length - 1)) {
wx.hideLoading();
}
App.serverErrorTip('上傳圖檔失敗');
}
},
fail: function (res) {
fail++;
if (i == (data.length - 1)) {
wx.hideLoading();
}
},
complete: function () {
i++;
if (i == data.length) { //當圖檔傳完時,停止調用
console.log('執行完畢');
console.log('成功:' + success + " 失敗:" + fail);
that.isClicking = false;
} else {//若圖檔還沒有傳完,則繼續調用函數
data.i = i;
data.success = success;
data.fail = fail;
that.uploadimg(data);
}
}
});
},