效果圖
部分源代碼
js文件:
var uploadPicture = require('../Frameworks/common.js') //獲取應用實例 const app = getApp() data:{ // 上傳的案例圖片集合 uploadImages: [], // 設置上傳案例圖片的最大數目 maxImages: 9, // 案例圖片數目是否達到了最大數目 isMaxImagesNum: false, }, // 選擇圖片 chooseImageTap: function() { let _this = this; wx.showActionSheet({ itemList: ['從相冊中選擇', '拍照'], itemColor: "#f7982a", success: function(res) { if (!res.cancel) { if (res.tapIndex == 0) { _this.chooseWxImage('album') } else if (res.tapIndex == 1) { _this.chooseWxImage('camera') } } } }) }, // 選圖 chooseWxImage: function(type) { let _this = this; var picsItems; wx.chooseImage({ // 相關屬性設置 count: _this.data.maxImages, sizeType: ['original', 'compressed'], sourceType: [type], success: function(res) { var imgsrc = res.tempFilePaths; // concat數組連接,且不會改變現有數組 var picss = _this.data.uploadImages.concat(imgsrc); var imagesArr = ''; if (picss.length >= _this.data.maxImages) { _this.setData({ isMaxImagesNum: true }); } // 判斷選擇的數量是否超過設定數量 let num = picss.length <= _this.data.maxImages ? picss.length : _this.data.maxImages; for (var i = 0; i < num; i++) { imagesArr += '{"imgurl":"' + picss[i] + '"},'; } imagesArr = JSON.parse('[' + imagesArr.substring(0, imagesArr.length - 1) + ']'); _this.setData({ uploadImages: picss, picsItems: imagesArr }); } }) }, // 預覽所選圖片 selImagePre: function(e) { let _this = this; wx.previewImage({ urls: this.data.uploadImages, current: e.currentTarget.dataset.src }) }, // 圖片上傳 submitAction: function() { // 上傳所選圖片 uploadPicture.uploadimg({ // 傳圖同時攜帶的參數 url: app.globalData.baseUrl + 'freePeopleDemoImgs.php', path: _this.data.uploadImages, name: 'caseImages', date: Date.now(), }) },
common.js
function uploadimg(data) { console.log(data.date) 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: data.name, formData: { // 同時上傳userId和當前時間 userId: app.globalData.userId, date: data.date, }, success: (resp) => { success++; app.globalData.xqimgList += resp.data + ","; }, fail: (res) => { fail++; console.log('fail:' + i + "fail:" + fail); }, complete: () => { i++; if (i == data.path.length) { // 圖片傳完時停止調用 } else { // 圖片還沒有傳完繼續調用函數 data.i = i; data.success = success; data.fail = fail; that.uploadimg(data); } } }); } module.exports = { uploadimg: uploadimg, }
源碼:https://download.csdn.net/download/yimjune/10757386
原文:https://blog.csdn.net/feng2qing/article/details/81276860