小程式方法-上傳多上圖片
阿新 • • 發佈:2018-12-27
//資料 data: { imgUrl:[], imgname:[], }, //上傳方法 //<view class="pic_add" bindtap='imgupload'><image src="/images/add.png" mode="widthFix"></image></view> imgupload:function () { var that = this; var count = 6 - parseInt((that.data.imgUrl).length); if( count == false ) { wx.showToast({ title: '最多上傳6張', duration: 1500 }) return false; } wx.chooseImage({ count: 1, sizeType: ['compressed'], success: function (res) { var tempFilePaths = res.tempFilePaths; var i = 0; //第幾個 var length = res.tempFilePaths.length; //總共個數 var successUp = 0; //成功個數 var failUp = 0; //失敗個數 that.uploadImg(tempFilePaths, successUp, failUp, i, length); } }) }, uploadImg: function (tempFilePaths, successUp, failUp, i, length) { var that = this; var token = wx.getStorageSync('token'); wx.uploadFile({ url: _data.get_api_imgupload, //僅為示例,非真實的介面地址 filePath: tempFilePaths[i], name: 'file', header: { 'content-type': 'multipart/form-data', 'Authorization': token }, success: function (res) { //console.log(res); var srcArr = that.data.imgUrl; srcArr.push(data.data.src); var imgname = that.data.imgname; imgname.push(data.data.name); that.setData({ imgUrl: srcArr, imgname: imgname }); }, complete: () => { i++; if (i == length) { return; } else { //遞迴呼叫uploadDIY函式 if (!that.data.isuploaderror) { this.uploadImg(tempFilePaths, successUp, failUp, i, length); } } } }) }, //刪除 //<view class="pic_dle" data-id="{{key}}" data-name="{{imgname[key]}}" bindtap='remImg'><image src="/images/dle.png" mode="widthFix"></image></view> remImg:function (e) { var that = this; var dataset = e.currentTarget.dataset; var Index = dataset.id; var name = dataset.name; //通過`index`識別要刪除第幾條資料,第二個資料為要刪除的專案數量,通常為1 that.data.imgUrl.splice(Index, 1); that.data.imgname.splice(Index, 1); //渲染資料 that.setData({ imgUrl: that.data.imgUrl, imgname: that.data.imgname }); var url = _data.get_api_imgdel; var data = {'name': name}; _httpHelper.httpPost(url, data, function (res) {}); },