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

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

十一、上传与下载

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

 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+'\r\n'+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链接列表

     })

 

 }

相关文章
|
15天前
|
小程序 开发工具 Android开发
微信小程序开发工具的使用,各个配置文件详解,小程序开发快速入门(二)
微信小程序开发工具的使用,各个配置文件详解,小程序开发快速入门(二)
|
15天前
|
小程序 JavaScript 开发工具
微信小程序开发工具的使用,各个配置文件详解,小程序开发快速入门(一)
微信小程序开发工具的使用,各个配置文件详解,小程序开发快速入门(一)
|
2月前
|
小程序 JavaScript 前端开发
微信小程序快速入门03
微信小程序快速入门03
|
2月前
|
JSON 小程序 JavaScript
微信小程序快速入门02(含案例)
微信小程序快速入门02(含案例)
|
4月前
|
小程序 前端开发 JavaScript
微信小程序快速入门01(含案例)
微信小程序快速入门01(含案例)
124 1
|
1月前
|
小程序 前端开发 API
微信小程序全栈开发中的异常处理与日志记录
【4月更文挑战第12天】本文探讨了微信小程序全栈开发中的异常处理和日志记录,强调其对确保应用稳定性和用户体验的重要性。异常处理涵盖前端(网络、页面跳转、用户输入、逻辑异常)和后端(数据库、API、业务逻辑)方面;日志记录则关注关键操作和异常情况的追踪。实践中,前端可利用try-catch处理异常,后端借助日志框架记录异常,同时采用集中式日志管理工具提升分析效率。开发者应注意安全性、性能和团队协作,以优化异常处理与日志记录流程。
|
1月前
|
小程序 安全 数据安全/隐私保护
微信小程序全栈开发中的身份认证与授权机制
【4月更文挑战第12天】本文探讨了微信小程序全栈开发中的身份认证与授权机制。身份认证包括手机号验证、微信登录和第三方登录,而授权机制涉及角色权限控制、ACL和OAuth 2.0。实践中,开发者可利用微信登录获取用户信息,集成第三方登录,以及实施角色和ACL进行权限控制。注意点包括安全性、用户体验和合规性,以保障小程序的安全运行和良好体验。通过这些方法,开发者能有效掌握小程序全栈开发技术。
|
1月前
|
小程序 前端开发 JavaScript
微信小程序全栈开发中的PWA技术应用
【4月更文挑战第12天】本文探讨了微信小程序全栈开发中PWA技术的应用,PWA结合Web的开放性和原生应用的性能,提供离线访问、后台运行、桌面图标和原生体验。开发者可利用Service Worker实现离线访问,Worker处理后台运行,Web App Manifest添加桌面图标,CSS和JavaScript提升原生体验。实践中需注意兼容性、性能优化和用户体验。PWA技术能提升小程序的性能和用户体验,助力开发者打造优质小程序。
|
4天前
|
Web App开发 数据采集 移动开发
开发uniapp过程中对app、微信小程序与h5的webview调试
开发uniapp过程中对app、微信小程序与h5的webview调试
10 1
|
15天前
|
小程序 前端开发 JavaScript
轻松学会微信小程序开发(一)
轻松学会微信小程序开发(一)

热门文章

最新文章