微信小程序开发之路⑥

37、微信小程序文件操作

文件操作是小程序把文件存储到本地和查找本地消息的一种方法
文件操作属性:参考在线字典

<view class="container">
    <view class="page-section">
        <view class="control-title">保存文件</view>
        <button bindtap="saveFile">保存文件</button>
    </view>
    <view class="page-section">
        <view class="control-title">获取本地的缓存临时文件 </view>
        <button bindtap="getFileInfo">获取本地的缓存临时文件</button>
    </view>
    <view class="page-section">
        <view class="control-title">获取以存储的文件列表</view>
        <button bindtap="getSavedFiledList">获取以存储的文件列表</button>
    </view>
    <view class="page-section">
        <view class="control-title">清楚本地缓存文件</view>
        <button bindtap="removeSavedFile">清楚本地缓存文件</button>
    </view>

    <view class="page-section">
        <view class="control-title">打开文档</view>
        <button bindtap="openDocument">文档打开</button>
    </view>
</view>

// pages/index/index.js
Page({
    /**
     * 页面的初始数据
     */
    data: {},
    /**
     * 打开文档
     */
    openDocument() {
        //需要先下载文档
        wx.downloadFile({
            url: '', //docx,xls,ppt,pdf
            success(res) {
                const filePath = res.tempFilePath
                wx.openDocument({
                    filePath: filePath,
                    success(res) {
                        console.log('文件已经打开')
                    },
                })
            },
        })
    },
    /**
     * 清楚本地缓存文件
     */
    removeSavedFile() {
        //获取文件
        const fs = wx.getFileSystemManager()
        fs.getSavedFileList({
            success(res) {
                console.log(res)
                //删除
                if (res.fileList.length > 0) {
                    for (let i = 0; i < res.fileList.length; i++) {
                        fs.removeSavedFile({
                            filePath: res.fileList[i].filePath,
                            success(res) {
                                console.log('[success]', res)
                            },
                            fail(res) {
                                console.log('[fail]', res)
                            },
                            complete(res) {
                                console.log('[complete]', res)
                            },
                        })
                    }
                }
            },
        })
    },
    /**
     * 获取以存储的文件列表
     */
    getSavedFiledList() {
        const fs = wx.getFileSystemManager()
        fs.getSavedFileList({
            success(res) {
                console.log(res.fileList)
            },
        })
    },
    /**
     * 获取本地临时缓存文件
     *
     */
    getFileInfo() {
        wx.chooseImage({
            success: function (res) {
                const fs = wx.getFileSystemManager()
                fs.getFileInfo({
                    filePath: res.tempFilePaths[0],
                    //size以字节为单位
                    //digest 计算算法 md5/sha1 之后的一个值,默认md5
                    success(res) {
                        console.log(res.size)
                    },
                })
            },
        })
    },
    saveFile() {
        wx.chooseImage({
            success(res) {
                const tempFilePaths = res.tempFilePaths
                console.log(tempFilePaths)
                // 保存
                // 先创建一个对象
                const fs = wx.getFileSystemManager()
                fs.saveFile({
                    tempFilePath: tempFilePaths[0],
                    success(res) {
                        const savedFilePath = res.savedFilePath
                        console.log(savedFilePath)
                        //     //图片存储后的路径
                        //   //windows:C:\Users\wangyan\AppData\Local\微信web开发者工具\User Data
                    },
                })

                // 保存到相册
                // wx.saveImageToPhotosAlbum({
                //   filePath: tempFilePaths[0],
                //   success(res) {
                //     const saveFielPath = res.savedFilePath
                //     console.log(saveFielPath)
                //   }

                // })
                //保存至视频目录

                // wx.saveVideoToPhotosAlbum({
                //   filePath: tempFilePaths[0],//视频文件的临时路径
                //   success(res){
                //     wx.showToast({
                //       title: '保存成功',
                //     })
                //   }
                // })
            },
        })
    },
})

38、微信小程序数据缓存(实现页面数据的交换)

本地数据的存储是通过数据缓存来实现的。通过键值对的方式来完成存储
数据缓存的生命周期跟小程序本身一致

数据存储大小上线为 10m

数据缓存分同步和异步双接口调用

<button bindtap='setStorage'>设置缓存</button>
<button bindtap='removeStorage'>移除缓存</button>
<button bindtap='getStorageInfo'>获取当前缓存里的数据信息</button>
<button bindtap='clearStorage'>清除缓存</button>


Page({
  /**
   * 页面的初始数据
   */
  data: {
  },
  /**
   * 清除缓存数据
   * Sync:同步
   */
  clearStorage(){
    wx.clearStorage()
  },
  /**
   * 设置缓存
   */
  setStorage(){
    wx.setStorage({
      key: 'name',
      data: 'tom',
      success(){
        console.log('storage is saved')
      }
    })
  },
  /**
   * 移除缓存
   */
  removeStorage(){
    wx.removeStorage({
      key: 'name',
      success: function(res) {
        console.log('storage name is none')
      },
    })
  },
  /**
   * 获取缓存里的数据信息
   */
  getStorageInfo(){
    wx.getStorageInfo({
      success: function(res) {
        console.log(res)
      },
    })
  },
  /**
   * 生命周期的加载
   */
  onLoad(options){
    wx.getStorage({
      key: 'storageVal',
      success: function(res) {
        console.log(res)
      },
    })
  }
})

// demo
<view class='container'>
<view class='btn-area'>
  <navigator url='/pages/index/index'>跳转到新的页面</navigator>
  <view class='section'>
    <input placeholder='输入信息' bindblur='getInput'></input>
    <button bindtap='navi'>存储</button>
  </view>
</view>
</view>

Page({
  inputVal:'',
  /**
   * 页面的初始数据
   */
  data: {
  },
  /**
   * 跳转
   */
  navi(){
    wx.setStorageSync('storageVal', this.inputVal)
  },
  /**
   * 获取数据
   */
  getInput(e){
    console.log(e.detail.value)
    this.inputVal = e.detail.value
  }
})

39、微信小程序数据传输的方式

数据传输方式有如下几种

1.本地缓存传输

2.导航标记传输  String
    不能传复杂的数据类型(Array, Object)
3.api 跳转 (外部数据来)
<button bindtap='setStorage'>设置缓存</button>
<button bindtap='removeStorage'>移除缓存</button>
<button bindtap='getStorageInfo'>获取当前缓存里的数据信息</button>
<button bindtap='clearStorage'>清除缓存</button>

Page({
  /**
   * 页面的初始数据
   */
  data: {
  },
  /**
   * 清除缓存数据
   * Sync:同步
   */
  clearStorage(){
    wx.clearStorage()
  },
  /**
   * 设置缓存
   */
  setStorage(){
    wx.setStorage({
      key: 'name',
      data: 'tom',
      success(){
        console.log('storage is saved')
      }
    })
  },
  /**
   * 移除缓存
   */
  removeStorage(){
    wx.removeStorage({
      key: 'name',
      success: function(res) {
        console.log('storage name is none')
      },
    })
  },
  /**
   * 获取缓存里的数据信息
   */
  getStorageInfo(){
    wx.getStorageInfo({
      success: function(res) {
        console.log(res)
      },
    })
  },
  /**
   * 生命周期的加载
   */
  onLoad(options){
    wx.getStorage({
      key: 'storageVal',
      success: function(res) {
        console.log(res)
      },
    })
  }
})


<view class='container'>
<view class='btn-area'>
  <navigator url='/pages/index/index'>跳转到新的页面</navigator>
  <view class='section'>
    <input placeholder='输入信息' bindblur='getInput'></input>
    <button bindtap='navi'>存储</button>
  </view>
</view>
</view>

Page({
  inputVal:'',
  /**
   * 页面的初始数据
   */
  data: {
  },
  /**
   * 跳转
   */
  navi(){
    wx.setStorageSync('storageVal', this.inputVal)
  },
  /**
   * 获取数据
   */
  getInput(e){
    console.log(e.detail.value)
    this.inputVal = e.detail.value
  }
})

40、罗盘

<view class='container'>
  <view class='text'>
    <text>请您远离磁场干扰源</text>
    <text>并按下图所示校准指南针</text>
  </view>
  <view class='img'>
  <image src='../../images/tip.jpg' class='tip-pic'></image>
  <button class='tip-btn' bindtap='jump'>我知道了</button>
  </view>
</view>

  jump(){
    wx.redirectTo({
      url: '../compass/compass',
    })
  },

<view class='container'>
  <view class='text'>
    <text>{{direction}}</text>
    <text>{{angle}}°</text>
  </view>
  <view class='pic'>
    <image src='../../images/compass.png' style='transform:rotate({{rotate}}deg)'></image>
  </view>
</view>


// pages/compass/compass.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    direction:"--",
    angle:"--",
    rotate:''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //开始罗盘操作
    let that = this
    wx.onCompassChange(function(res){
      //罗盘数据保留小数2位
      //console.log(res)
      let directions = res.direction.toFixed(2)
      let radios =res.direction.toFixed(0)
      that.setData({
        angle:directions,
        rotate: 360 - radios,
        direction: check(radios)
      })
    })
    //判断手机是否有陀螺仪
    /**
     * 外部检测,如果没有陀螺仪,代码是不会进入wx.onCompassChange事件的
     * 使用settimeout包裹代码,负责代码立即执行都会弹窗
     */
    setTimeout(() => {
      if (that.data.direction == '--' && that.data.angle == '--') {
        wx.showToast({
          title: '您的手机没有带电子罗盘或被禁用',
          icon: 'loading',
          duration: 5000,
          mask: true
        })
      }
    }, 3000);
    /**
       * 方向判断函数
       */
    function check(i){
      if (15 < i && i <= 75) {
        return '东北'
      } else if (75 < i && i < 105) {
        return '正东'
      } else if (105 < i && i < 195) {
        return '东南'
      } else if (165 < i && i < 195) {
        return '正南'
      } else if (195 < i && i <= 255) {
        return '正西'
      } else if (285 < i && i < 345) {
        return '西北'
      } else {
        return '正北'
      }
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title:'我现在面向 '+ this.data.direction+" 方向,点我使用迷你指南针为您指引方向!",
      path:'/pages/compass/compass'
    }
  }
})

wifi
<view class='container'>
  <view class='text'>一键连接WIFI</view>
  <form bindsubmit='connectWifi'>
    <view class='form'>
      <view class='section'>
        <text>wifi账户</text>
        <input placeholder='请输入wifi账户' name='wifiname'></input>
      </view>
      <view class='section'>
        <text>wifi密码</text>
        <input placeholder='请输入wifi密码' name='wifipwd' password></input>
      </view>
      <button form-type='submit' type='primary'>连接WIFI</button>
      <button bindtap='startSearch'>搜索附件wfii</button>
  </view>
  <view>
    <block wx:for='{{wifiList}}' wx:key='{{index}}'>
      <view>
        <text>{{item.SSID}}</text>
      </view>
    </block>
  </view>
  </form>
</view>

// pages/index/index.js
Page({
  userWifiName: '',
  userWifiPwd: '',
  /**
   * 页面的初始数据
   */
  data: {
    wifiList:[]
  },
  /**
   * 连接wifi
   */
  connectWifi(e){
    //获取用户输入的wifi账户和密码
   this.userWifiName = e.detail.value.wifiname
   this.userWifiPwd = e.detail.value.wifipwd
   let that = this
   //检测手机型号,获得系统信息
   wx.getSystemInfo({
     success: function(res) {
       let system = ''
       if(res.platform == 'android'){
         system = parseInt(res.system.substr(8))
       }
       if(res.platform == 'ios'){
         system = parseInt(res.system.substr(4))
       }
       if(res.platform == 'andorid' && system < 6){
         //提示手机不支持
         wx.showToast({
           title: '安卓当前手机版本不支持',
         })
         return
       }
       if(res.platform == 'ios' && system < 11.2){
         wx.showToast({
           title: '苹果手机当前版本不支持',
         })
         return
       }
       //初始化Wifi模板
       that.startWifi()
     },
   })
  },
  /**
   * 初始化WIFI模块
   */
  startWifi(){
    let that = this
    wx.startWifi({
      success(){
        //连接
        that.Connected()
      },
      fail(res){
        wx.showToast({
          title: '接口调用失败',
        })
      }
    })
  },
  /**
   * 连接wifi
   */
  Connected(){
    let that = this
    wx.connectWifi({
      SSID: this.userWifiName,//wifi账户名
      password: this.userWifiPwd,//wifi连接密码
      success(res){
        wx.showToast({
          title: 'wifi连接成功',
          duration: 2000
        })
      },
      fail(res){
        console.log(res)
        wx.showToast({
          title: 'wifi连接失败',
          duration: 2000
        })
      }
    })
  },
  /**
   * 搜索wifi
   */
  startSearch(){
    const getWifiList = () => {
        wx.getWifiList({
          success: (res) => {
            wx.onGetWifiList((res) => {
              const wifiList = res.wifiList
                .map(wifi => {
                  const strength = Math.ceil(wifi.signalStrength * 4)
                  return Object.assign(wifi, { strength })
                })
              this.setData({
                wifiList
              })
            })
          },
        })
    }
    const startWifi = () => {
      wx.startWifi({
        success:getWifiList,
        fail(res){
          console.error(res)
        }
      })
    }
    //获取系统信息
    wx.getSystemInfo({
      success(res) {
        const isIOS = res.platform === "ios"
        if (isIOS){
          wx.showModal({
            title: '提示',
            content: '由于系统限制,ios用户请手动先进入系统Wifi页面,然后返回小程序',
            showCancel: false,
            success(){
              //开启wifi搜索
              startWifi()
            }
          })
          return
        }
        startWifi()
      },
    })
  }
})

加速计
;<view class="panel_root">
    <view class="view_top" animation="{{animation1}}">
        <image class="img_top" src="{{img_url}}"></image>
    </view>
    <view class="view_bottom" animation="{{animation2}}">
        <image class="img_bottom" src="{{img_url}}"></image>
        <view class="panel_bottom">
            <view
                class="panel_loading"
                style="display:{{hasResutl==0?'block':'none'}}"
            >
                <image class="img_loading" src="{{loading}}"></image>
                <text class="text_lable">正在搜索同意时刻摇晃手机的人</text>
            </view>
            <view
                class="panel_result"
                style="display:{{hasResutl==1?'block':'none'}}"
            >
                哈哈
            </view>
        </view>
    </view>
    <button class="btn_test" bindtap="startAnimation">
        测试
    </button>
</view>

Page({
    /**
     * 页面的初始数据
     */
    data: {
        hasResutl: -1,
        bar_state: 0,
        winWidth: 0,
        winHeight: 0,
        img_url:
            'https://www.demomaster.cn/eatbar/public/static/img/yaoyiyao/img_yaoyiyao.png',
        loading:
            'https://www.demomaster.cn/eatbar/public/static/img/yaoyiyao/small_loading.gif',
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this
        that.initAnimation()
        //重力加速度
        wx.onAccelerometerChange(function (res) {
            //console.log(res.x)
            //console.log(res.y)
            //console.log(res.z)
            if (res.x > 0.7 && res.y > 0.7) {
                // wx.showToast({
                //   title: '摇一摇成功',
                //   icon: 'success',
                //   duration: 2000
                // })
                that.startAnimation()
            }
        })
        var that = this
        //获取系统信息
        wx.getSystemInfo({
            success: function (res) {
                that.setData({
                    winWidth: res.windowWidth,
                    winHeight: res.windowHeight,
                })
            },
        })
    },
    initAnimation: function () {
        var that = this
        //实例化一个动画
        this.animation1 = wx.createAnimation({
            // 动画持续时间,单位ms,默认值 400
            duration: 400,
            /**
             * linear 动画一直较为均匀
             * ease 从匀速到加速在到匀速
             * ease-in 缓慢到匀速
             * ease-in-out 从缓慢到匀速再到缓慢
             *
             * step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
             * step-end 保持 0% 的样式直到动画持续时间结束 一闪而过
             */
            timingFunction: 'ease',
            // 延迟多长时间开始
            // delay: 100,
            /**
             * 以什么为基点做动画 效果自己演示
             * left,center right是水平方向取值,对应的百分值为left=0%;center=50%;right=100%
             * top center bottom是垂直方向的取值,其中top=0%;center=50%;bottom=100%
             */
            transformOrigin: 'left top 0',
            success: function (res) {
                console.log(res)
            },
        })
        //实例化一个动画
        this.animation2 = wx.createAnimation({
            // 动画持续时间,单位ms,默认值 400
            duration: 400,
            /**
             * linear 动画一直较为均匀
             * ease 从匀速到加速在到匀速
             * ease-in 缓慢到匀速
             * ease-in-out 从缓慢到匀速再到缓慢
             *
             * step-start 动画一开始就跳到 100% 直到动画持续时间结束 一闪而过
             * step-end 保持 0% 的样式直到动画持续时间结束 一闪而过
             */
            timingFunction: 'ease',
            // 延迟多长时间开始
            // delay: 100,
            /**
             * 以什么为基点做动画 效果自己演示
             * left,center right是水平方向取值,对应的百分值为left=0%;center=50%;right=100%
             * top center bottom是垂直方向的取值,其中top=0%;center=50%;bottom=100%
             */
            transformOrigin: 'left top 0',
            success: function (res) {
                console.log(res)
            },
        })
    },
    /**
     *位移
     */
    startAnimation: function () {
        var that = this
        //x轴位移100px
        var h1 = '35%'
        var h2 = '65%'
        if (this.data.bar_state == 1) {
            h1 = '40%'
            h2 = '40%'
            setTimeout(function () {
                that.setData({
                    //输出动画
                    bar_state: 0,
                    hasResutl: 0,
                })
                setTimeout(function () {
                    that.setData({
                        hasResutl: 1,
                    })
                }, 4000)
            }, 400)
        } else {
            h1 = '25%'
            h2 = '55%'
            this.setData({
                bar_state: 1,
            })
            setTimeout(function () {
                that.startAnimation()
            }, 600)
        }
        this.animation1.height(h1).step()
        this.animation2.top(h2).step()
        this.setData({
            //输出动画
            animation1: that.animation1.export(),
            animation2: that.animation2.export(),
        })
    },
})
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值