微信小程序快速入门开发指南(三)

2024-06-20 13:35:37 浏览数 (1)

十一、上传与下载

  上传一个文件,举例如下:

  impFormExcel: function (e) {

 var that = this;

 //调出微信界面,从好友中选择已经发送过的文件

    wx.chooseMessageFile({

      count: 1,     只能选择一个文件

      type: 'file',    类型为文件

      success(res) {

        wx.showLoading({

          title: '正在上传....',

        })

        wx.uploadFile({

          url: app.globalData.uploadfileUrl,  //后台接收上传文件的接口

          filePath: res.tempFiles[0].path,   //获得手机文件的目录

          name: 'file',

          formData: {

          },

          success(res2) {

            wx.hideLoading();

       //上传成功执行函数

            that.importexcel('wxmp_ImpExcelForForm',that.data.cid, res.tempFiles[0].path.slice(9));  最后为上传到服务器的为文件名

//do something

          },

          fail(res2) {

            wx.hideLoading();

            wx.showModal({

              title: '',

              content: res2.errMsg,

              showCancel: false,

            })

          }

        })

      }

    })

  },

服务器端的处理

string filename = get_uft8(Request["upfile"]);

string path = Request.PhysicalApplicationPath "\app_data\wxmp\uploadfiles\" filename;

下载一个文件

downloadfile: function (e) {

    wx.showLoading({

      title: '文件下载中...',

    })

var that = this;

var dfile = e.currentTarget.dataset.url;    //在控件上设置好的参数

    wx.downloadFile({

      url: app.globalData.mapurl 'HelpCenter/wxmp/downloads/' dfile,

      success: function(res){

        wx.hideLoading();

var filePath = res.tempFilePath

        wx.showLoading({

          title: '文件预览中...',

        })

        //成功后使用微信的打开文档功能进行手机预览

        wx.openDocument({

          filePath: filePath,

          success: function (res) {

            wx.hideLoading();

          },

          fail:function(res){

            wx.hideLoading();

            wx.showToast({

              title: '预览失败',

              duration:3000

            })

          }

        })

      },

      fail:function(res){

        wx.hideLoading();

        wx.showToast({

          title: '下载失败',

          duration: 3000

        })

      }

    })

  },

十二、小程序的页面注册与访问

(1)每开发一个功能页面,需要在app.json配置文件pages节点里手动添加,否则程序会报错,如下:

"pages": [

"pages/index/index",

"pages/pubSign/pubSign",

  ],

(2)由一个页面去调用另一个页面如下:

navpage:function(e){

    wx.navigateTo({

      url: '../allowSignUpList/allowSignUpList?cid=XXX',

    })

  }

    请注意网址的页面部分可以不用输入.wxml,传参是标准格式。

(3)目标页面访问传递的参数

在页面的onload事件里,函数添加 options 即可接收上一页面传递过来的参数集合

  onLoad: function (options) {

var that=this;

if(options.cid!=undefined){  

this.setData({cid:options.cid });

}

十三、小程序的一些注意事项

(1)小程序所有微信接口函数是异步的,不是同步的

   如调用模式窗口如下:

   wx.showModal({

                  title: '',

                  content: res.data.errmsg,

                  showCancel: false,

                })

        that.setData({querytip: res.errMsg});

    不要试图等待模式窗口结束交互才执行下一句,正确应该改造为

     wx.showModal({

                  title: '',

                  content: res.data.errmsg,

                  showCancel: false,

      success: function (res) {

            if(res==’ok’){

                                           that.setData({querytip: res.errMsg});

                                          }

        }

     })

十四、小程序界面通过if判断输出不同的wxml标记

<block wx:if="{{item.fType=='多行文字'}}">

        <textarea name='{{item.sysfName}}'  maxlength='{{item.fLength}}' bindinput='ipt' data-index="{{index}}" value='{{item.fvalue}}' class="stdinput" ></textarea>

</block>

<block wx:elif="{{item.valueList!=''}}">

        <picker name='{{item.sysfName}}'    maxlength='{{item.fLength}}'  bindchange='iselect' data-index="{{index}}" range='{{item.valueList}}'  placeholder='{{item.allowNull}}'  class="stdlabel" >{{item.fvalue==''?'':''}}{{queryresult[index].fvalue}}<image  src='../../images/rightArrow.jpg' mode='aspectFit' style='width:20px;height:20px;background-color:transparent;' ></image></picker>

</block>

<block wx:else>

        <input name='{{item.sysfName}}'  maxlength='{{item.fLength}}' bindinput='ipt' data-index="{{index}}" value='{{item.fvalue}}' placeholder='{{item.allowNull}}' class="stdinput" ></input>

      </block>

</block>

十五、几种微信接口函数

  1. 获取openid

    getopenid:function(){

    this.setData({ motto: '正在验证登录...' });

    var that = this;

    wx.login({

        success: res => {

            if (res.code) {

              //调用request请求api转换登录凭证

              wx.request({

                  url: 'https://api.weixin.qq.com/sns/jscode2session',

                  data: {

                      //小程序唯一标识

                    appid: app.globalData.appid,

                      //小程序的 app secret

                    secret: app.globalData.secret,

                      grant_type: 'authorization_code',

                      js_code: res.code

                  },

                  method: 'GET',

                  header: { 'content-type': 'application/json' },

                  success: function (res) {

                    // console.log(res.data.openid) //获取openid

                    app.globalData.sessionKey = res.data.session_key;

                    app.globalData.openId = res.data.openid;

                    app.globalData.unionId=res.data.unionid;

                    if (app.globalData.openId != '') {

                      that.wxmp_syncuser('', '', '注册用户','','','','');

                      that.setData({ LogonBtnDisplay: 'none' });

                    }

                  },fail:function(res){

                          that.setData({ motto: 'getting fail...' });

                          }

              })

            } else { that.setData({ motto: 'getting code fail...' });}

      }, fail: res => { that.setData({ motto: 'res finish...' });}

    })//login

  }//getopenid

2.获取当前手机地理位置

getlocation:function(){

    var that=this;

    wx.showLoading({

      title: '正在定位...',

    })

    wx.getLocation({

      type: 'gcj02',

      success: function (curres) {

        wx.hideLoading();

        that.scancode(curres.latitude 'rn' curres.longitude);

      },

      fail: function (res) {

        wx.hideLoading();

        wx.showModal({

          title: '',

          content: res.errMsg,

          showCancel: false,

        })

      }

    }

    )

  }

3.调用扫一扫

scancode:function(_gps){

    var that=this;

    onlyFromCamera:true,

    wx.scanCode({

      success:function(res){

that.wxmp_SignFromScanCode(app.globalData.openId,res.result,_gps);

      },

      fail:function(res){},

      complete:function(res){}

    })

  }//scancode

4.获取用户手机号

<button class="bindBtn" open-type='getPhoneNumber' bindgetphonenumber='getPhoneNumber' >

      <text>绑手机</text>

</button>

请注意先执行open-type事件,这是微信提供的固定类型事件,然后再执行bindgetphonenumber事件,这是用户自定义调用函数据名

getPhoneNumber: function (e) {

    var that = this;

    var encrypteddata = e.detail.encryptedData

    var ivs = e.detail.iv

    wx.request({

      url: app.globalData.apiurl,

      method: "POST",

      data: {

        gettype: 'desdata',

        session_key: app.globalData.sessionKey,

        encryptedData: encrypteddata,

        iv: ivs

      },

      header: {

        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'

      },

      success: function (res) {

        if(res.data.phoneNumber==undefined){

          wx.showModal({

            title: '',

            content: '绑定失败!您已经拒绝授权获取手机号。',

            showCancel: false,

          });

          return;

        }

        if (res.data.phoneNumber != '') {

          that.setData({ us3: '已更新' });

          that.wxmp_syncuser('', res.data.phoneNumber, '更新手机号','','','','');

        } else {

          wx.showModal({

            title: '',

            content: '获取绑定手机号失败。',

            showCancel: false,

          });

        }

      },

      fail: function (res) {

        wx.showModal({

          title: '',

          content: res.errMsg,

          showCancel: false,

        });

      }

    })

  }//getphonenumber

5.获取用户微信昵称头像

<button class="bindBtn" open-type='getUserInfo' bindgetuserinfo='setuserinfo'  >   <view >绑昵称</view>

</button>

setuserinfo:function(){

  wx.showLoading({

    title: '更新中...',

  })

  var that=this;

  wx.getUserInfo({

    lang:'zh_CN',

    success: function (resinfo) {

      that.setData({ avatarUrl: resinfo.userInfo.avatarUrl });

      that.setData({ nickName: resinfo.userInfo.nickName });

      },fail:function(res){

      wx.showModal({

        title: '',

        content: res.errMsg,

        showCancel: false,

      });

      wx.hideLoading();

    }

  });

}

6.调用手机相册选择一个图片并在控件通过BASE64编码显示出来

wx.chooseImage({

        count: 1, // 默认9

        sizeType: ['compressed'],

        success:function(res) {

        self.setData({ Base64: null });

        wx.showLoading({

          title: '上传中请稍候',

        });

        wx.getFileSystemManager().readFile({

          filePath: res.tempFilePaths[0], //选择图片返回的相对路径

          encoding: 'base64', //编码格式

          success: res2 => { //成功的回调

            var file = res.tempFilePaths[0];

            var exname=file.substring(file.lastIndexOf('.') 1);

 self.setData({ Base64: 'data:image/' exname ';base64,' res2.data });

            wx.hideLoading();

            wx.showToast({

              title: '上传成功' exname,

            })

          },

          fail: res2 => { //成功的回调

            wx.hideLoading();

            wx.showToast({

              title: res2.errMsg,

              duration:3000

            })

          }

          })

      }

    })

  }

7.调用微信预览图片功能

控件代码片断

<image bindtap='previewImage' src='{{Base64}}'  data-id='1' style=''></image>

data-id对应e.currentTarget.dataset.id

调用函数

previewImage:function(e){

      var that=this;

      var img=null;

      if (e.currentTarget.dataset.id=='1'){

        img = that.data.Base64;

      }

      if (e.currentTarget.dataset.id == '2') {

        img = that.data.Base64;

      }

    var imglist = [];

    imglist.push(that.data.Base64);  //列表多可以预览多个图片

wx.previewImage({

        current: img ,//base64

        urls: imglist //需要预览的图片http链接列表

      })

  }

0 人点赞