//调用相册等选择图片,得到图片的相对路劲
up_img: function () { var that = this; wx.chooseImage({ count: 1, // 默认9 sizeType: ['compressed'], sourceType: ['album', 'camera'], success: function (res) { var tempFilePaths = res.tempFilePaths; upload(that, tempFilePaths); } }) }
//把图片上传到服务器
function upload(page, path) { wx.showToast({ icon: "loading", title: "正在上传" }), wx.uploadFile({ url: app.globalData.url + 'index.php?g=api&m=api&a=img_upload_api', filePath: path[0], name: 'file', formData: { openid: wx.getStorageSync('openid'), is_type: 1 }, success: function (res) { if (res.statusCode != 200) { wx.showModal({ title: '提示', content: '上传失败', showCancel: false }) return; } var res_data = JSON.parse(res.data); // poster_src = res_data.data; page.setData({ poster_src: res_data.data }); }, fail: function (e) { console.log(e); wx.showModal({ title: '提示', content: '上传失败', showCancel: false }) }, complete: function () { wx.hideToast(); //隐藏Toast } }); }
以上是上传一张图片,下面是上传多张图片,需要注意的是filePath必须是字符串。
//调用相册等选择图片,得到图片的相对路劲 up_img: function () { var that = this; wx.chooseImage({ count: 9, // 默认9 sizeType: ['compressed'], sourceType: ['album', 'camera'], success: function (res) { console.log(res.tempFilePaths); var successUp = 0; //成功个数 var failUp = 0; //失败个数 var length = res.tempFilePaths.length; //总共个数 var i = 0; //第几个 that.upload(res.tempFilePaths, successUp, failUp, i, length); } }) }
//上传图片到服务器 upload: function (filePaths, successUp, failUp, i, length) { var that = this; wx.uploadFile({ url: app.globalData.url + 'index.php/api/Home/tpupload', filePath: filePaths[i], name: 'file', success: function (res) { var res_data = JSON.parse(res.data); if (res_data.status == 200) { successUp++; var arrimg = that.data.poster_src; var now_upload_img = that.data.upload_img arrimg.push(filePaths[i]); now_upload_img.push(res_data.data); // console.log("now_upload_img=" + now_upload_img); // console.log("arrimg=" + arrimg); that.setData({ poster_src: arrimg, upload_img: now_upload_img }); } else { wx.showToast({ title: res_data.error, icon: 'loading', duration: 1000 }) } }, fail: function (e) { failUp++; wx.showToast({ title: '请求失败', icon: 'loading', duration: 1000 }) }, complete: function () { i++; if (i == length) { // page.showToast('总共' + successUp + '张上传成功,' + failUp + '张上传失败!'); wx.showToast({ title: '总共' + successUp + '张上传成功,' + failUp + '张上传失败!', icon: 'loading', duration: 1000 }) } else { //递归调用uploadDIY函数 that.upload(filePaths, successUp, failUp, i, length); } } }) }
// 删除图片 delimg: function (e) { var imgs = this.data.poster_src; var index = e.currentTarget.dataset.index; imgs.splice(index, 1); this.setData({ poster_src: imgs }); }
前端页面展示图片的路劲是本地选择图片后得到的相对路劲,最后单击提交按钮上传所有东西时,图片这块要上传后台传来的图片地址,最后把所有图片上传给后台时数组形式出现问题之后是把所有图片拼接成字符串解决问题。
var upload_img_str = null; for (var i = 0; i < that.data.upload_img.length; i++) { if (i == 0) { upload_img_str = that.data.upload_img[i]; } else { upload_img_str += ',' + that.data.upload_img[i]; } }