微信小程序自我总结2,图片上传和Promise(微信小程序获取地理位置 微信小程序上传图片 微信小程序云存储 微信小程序setData性能)

菜鸟第二篇总结

文章目录

    • company.js
      • upcompanyImg
      • 第二点
      • upCloudDb

注册界面

company.js

const QQMapWX = require('../company/qqmap-wx-jssdk'); //获取地址的API的js文件引用
let qqmapsdk;
const db = wx.cloud.database(); // 这个容易忘掉,忘写就无法上传云数据库

Page({
  data: {
    companyName:'',
    companyAdress:'',
    simpleCompanyA:'',
    aheadTime:'',
    roomtimes:'',
    roomNumber:'',
    companyImg:[],
    fileids:[],
    openid:''
  },

  upcompanyImg:function(e){
    if(this.data.companyImg.length<4){
      wx.chooseImage({
        count: 4-this.data.companyImg.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res=>{
          // tempFilePath 可以作为img标签的src属性显示图片(小程序临时文件路径)
          // console.log(res)
          const tempFilePaths = res.tempFilePaths
          // console.log(tempFilePaths)
          this.setData({
            companyImg:this.data.companyImg.concat(tempFilePaths)
          }) 
        },
        fail:err=>{
          console.log(err);
          wx.showToast({
            title: '上传图片失败',
            mask:true,
            icon:'none'
          })
        }
      })
    }else{
      wx.chooseImage({
        count: 4,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res=>{
          const tempFilePaths = res.tempFilePaths
          this.data.companyImg=[];
          this.setData({
            companyImg:this.data.companyImg.concat(tempFilePaths)
          }) 
        },
        fail:err=>{
          console.log(err);
          wx.showToast({
            title: '上传图片失败',
            mask:true,
            icon:'none'
          })
        }
      })
    }
  },
  //判断图片上传个数4-数组长度,如果等于4,则清空数组并上传图片
  
  // 获取picker选择的时间
  bindTimeChange:function(e){
    // console.log(e)
    this.setData({
      roomtimes: e.detail.value
    })
  },
  
  // 微信获得经纬度
  getUserLocation:function(){
    qqmapsdk = new QQMapWX({
        key: 'XXXXXXXXX'
        // 腾讯定位提供的密匙,而不是小程序密匙
    });
    let vm = this;
    wx.getSetting({
      success: (res) => {
        // console.log(JSON.stringify(res))
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置,请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                    //再次授权,调用wx.getLocation的API
                    vm.getLocation();
                  } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },

  // 获取当前地理位置
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        // console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
        wx.showToast({
          title: '获取位置失败',
        })
      }
    })
  },
  
  // 获取后将其赋值给companyAdress
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        // console.log(JSON.stringify(res));
        let province = res.result.address_component.province
        let city = res.result.address_component.city
        let district =res.result.address_component.district
        let address_reference = res.result.address_reference.town.title
        let street = res.result.address_component.street
        let street_number =res.result.address_component.street_number
        vm.setData({
          companyAdress:province+city+district+address_reference+street+street_number
        })
      },
      fail: function (res) {
        console.log(res);
        wx.showToast({
          title: '获取位置失败',
        })
      },
    })
  },
  
  // 如果用户自己输入地址,则获取
  inputAdress:function(e){
    this.setData({
      companyAdress:e.detail.value
    })
  },
  
  // 获取用户填写的标志性地址
  inputsimpleA:function(e){
    this.data.simpleCompanyA=e.detail.value;
  },
  
  inputName:function(e){
    // console.log(e)
    this.setData({
      companyName:e.detail.value
    })
  },
  // 获取用户输入的饭店名称

  inputAheadTime:function(e){
    this.setData({
      aheadTime:e.detail.value
    })
  },
  // 获取用户输入的最大提前订餐时间

  inputNumber:function(e){
    this.setData({
      roomNumber:e.detail.value
    })
  },
  // 获取用户输入的包间个数

  upCloudDb:function(e){
    if(this.data.companyImg.length>=3 && this.data.companyName !== "" && this.data.companyAdress !== "" && this.data.aheadTime !== ""){
      wx.showLoading({
        title: '提交中',
        mask: true,
      })

      // 上传图片到云存储
      let promiseAarr = [];
      for(let i=0;i<this.data.companyImg.length;i++){
        promiseAarr.push(new Promise((reslove,reject)=>{
          let item = this.data.companyImg[i];
          let suff = /\.\w+$/.exec(item)[0];
          // console.log(suff)
          // 正则表达式,\w为匹配包括下划线的任何单词字符,等于"A-Za-z0-9_"
          wx.cloud.uploadFile({
            cloudPath: "Companyimg/"+ this.data.openid + '/' + new Date().getTime() + suff, 
            // 上传至云端的路径,不能在Companyimg前面加/
            filePath: item, // 小程序临时文件路径
            success: res => {
              // 返回文件 ID
              // console.log(res.fileID)
              this.setData({
                fileids:this.data.fileids.concat(res.fileID)
              })
              reslove();
            },
            fail:err=>{
              wx.showToast({
                title: '注册失败',
                mask:true,
                icon:'none'
              })
              console.log(err)
            }
          })
        }))
      }
      
      Promise.all(promiseAarr).then(res=>{
        // 插入数据
        db.collection("company").add({
          data:{
            companyName:this.data.companyName,
            companyAdress:this.data.companyAdress,
            simpleCompanyA:this.data.simpleCompanyA,
            aheadTime:this.data.aheadTime,
            roomtimes:this.data.roomtimes,
            roomNumber:this.data.roomNumber,
            fileids:this.data.fileids
          } 
        }).then(res=>{
          wx.hideLoading();
          wx.redirectTo({
            url: '../../companyuser/companyuser',
          })
        }).catch(err1=>{
          wx.hideLoading();
          wx.showToast({
            title: '注册失败',
            mask:true,
            icon:'none'
          })
          console.log(err1)
        })
      }).catch(err=>{
        console.error
        wx.showToast({
          title: '注册失败',
          mask:true,
          icon:'none'
        })
        console.log(err)
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '您的资料填写不完整',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
  // 上传用户信息上传照片到云存储,保存数据到数据库

  newgetLocation:function(e){
    wx.getSetting({
      success:res=>{
        res.authSetting['scope.userLocation'] == 'undefined'
      }
    })
    this.getUserLocation()
  },
  // 点击重新定位后清空getSetting

  onLoad: function (options) {
    this.getUserLocation();
    let app = getApp();
    this.data.openid=app.globalData.openid
  },
  // 加载时就获取用户地址
})

首先,介绍第一个函数

upcompanyImg

这就是一个上传图片的函数,但是一开始我还真的是写不出来,因为如果固定为4,一次性上传4张或以下图片是完全没得问题的,但是,一旦你先上传三张又想再上传,那麻烦就来了,你会发现用户最多还可以上传4张,这样一加就7张了,完全不可理喻。所以我的解决方法就是这:

count: 4-this.data.companyImg.length

先判断已上传的图片的数组的大小,如果小于4,则可以上传剩余图片个数,否则就又可以上传4张,并将原来的清空:

this.data.companyImg=[];
this.setData({
   companyImg:this.data.companyImg.concat(tempFilePaths)
 })

也就是,上传之前将图片数组清空,不然别人如果感觉上传的图片不好的话,想重新上传,不清空那么上传又会变多。

其实我感觉到了这种写法的不好,代码无法复用所以在另一个里面写的是这样的:

else{
	  this.data.companyImg=[];
      wx.chooseImage({
        count:4-this.data.companyImg.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: res=>{
          // tempFilePath可以作为img标签的src属性显示图片(小程序临时文件路径)
          // console.log(res)
          this.setData({
            companyImg:this.data.companyImg.concat(res.tempFilePaths)
          }) 
        },
        fail:err=>{
          console.log(err);
          wx.showToast({
            title: '上传图片失败',
            mask:true,
            icon:'none'
          })
        }
      })
    }

这样写,这可以把上传图片代码封装起来,然后就可以复用了。

第二点

我这个里面把输入信息都用了setData,其实这是完全没必要的,而且会影响页面性能,其实只需要:

this.data.XXXX=e.detail.value

后面的页面中我都改成了这种形式。

第二个值得讲的函数

upCloudDb

这个就是一个并行执行异步操作的上传函数,我一开始是完全写不出来的,只能到处照搬,不过写多了,理解就会了一点,慢慢的已经可以写出大部分代码了。

里面就是Promise的并行异步任务的处理,其代码是这样理解的:
1、创建一个数组,因为并行执行异步任务的参数就是数组,是任务的数组
2、每一个任务都是一个Promise对象(new Promise),拥有then,catch方法,简化异步操作 见该博客
在这里插入图片描述
3、既然都是Promise对象,那么它们就可以使用Promise.all()方法,当数组里面所有方法执行完成后,便可以执行后面的操作。

获取位置的代码是我直接copy过来的。

菜鸟的一点垃圾言论,望大佬指点江山,激扬文字

你可能感兴趣的:(微信小程序,微信小程序获取地理位置,微信小程序上传图片,微信小程序云存储,微信小程序setData性能)