微信小程序:5.写一个下载的组件

在前几篇的基础上,做出了下修改,逻辑大概是

1.检查是否路径,没有的话,则显示加载中的标识
2.检查用户是否开启保存相册/视频的权限(非初次),
3.检查用户当前网络状态,
4.开始下载任务,且若无progress返回,则取消progress的显示
5.下载成功,则根据尾缀进行保存(大部分的尾缀类型)保存(非初次)
6.提示下载成功/失败

代码大概是下面这样,

/**
 * 视频下载的组件
 * params:{
 * initshow:是否展示组件
 * initpath:下载路径,
 * }
 * call劫持时候似乎有点问题,所以改用const that=this
 */
let that;
const constant = require("../../utils/constant.js");
let downloadTask = null;
Component({
  data: {
    showProgress: true, //是否展示进度条
  },
  ready() {
    that = this;
  },
  /**
   * 组件的属性列表
   */
  properties: {
    // 是否显示下载的弹窗
    initshow: {
      type: Boolean,
      value: false,
      observer: function(newvalue, oldvalue) {
        //true则开始
        this.readyToDown();
      }
    },
    // 下载的路径
    initpath: {
      type: String,
      value: '',
      observer: function(newvalue, oldvalue) {
        // 如果没有下载的路径,并且当前已经打开弹窗了暂时显示转圈圈/
        this.readyToDown();
      }
    }
  },
  data: {
    progress: 0, //下载的进度
  },
  methods: {
    // 下载前的准备
    readyToDown() {
      wx.hideLoading();
      // 如果没有路径,则是显示滚动
      if (!this.data.initpath) {
        wx.showLoading({
          title: '正在准备下载~',
        })

      } else if (this.data.initshow) {
        this.getsetiingconfig();
      } else {}

    },
    // 获取用户有没有打开下载权限
    getsetiingconfig() {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting["scope.writePhotosAlbum"] === false) {
            getApp().globalData.powerfail({
              content: '保存视频失败,请检查是否在设置中允许使用相册功能',
              showCancel: true,
              confirmText: '前往设置',
              successcall: function() {
                wx.openSetting({})
              },
            })
            that.init();
          } else {
            this.checkNetworkStatus();
          }
        }
      })
    },
    // 下载并且保存至本地
    save() {
      downloadTask = wx.downloadFile({
        url: this.data.initpath,
        success: (downres) => {
          this.saveByType(downres.tempFilePath);
        },
        fail: () => {
          getApp().globalData.powerfail({
            content: '下载失败,请检查网络',
          })
        },
        complete: function() {
          that.init();
        }
      })
      // 监听下载的进度
      downloadTask.onProgressUpdate((onProgreesres) => {
        // 下载网页等,没有progress,则显示下载中
        if (onProgreesres.progress) {
          this.setData({
            showProgress: false,
            progress: 0
          })
          // 取消掉监听进度的事件
          downloadTask.offProgressUpdate(offProgressres => {})
        }
        this.setData({
          showProgress: true,
          progress: onProgreesres.progress || 0
        });
      })
    },
    // 取消下载
    cancelevent() {
      downloadTask ? downloadTask.abort() : '';
      that.init();
      wx.showToast({
        title: '已取消下载!',
        icon: "none",
        duration: 2000,
      });
    },
    //当前网络环境
    checkNetworkStatus() {
      wx.getNetworkType({
        success: (networkres) => {
          if (networkres.networkType === 'none') {
            wx.showToast({
              title: '当前无网络',
              icon: "none"
            })
          } else if (networkres.networkType === 'wifi') {
            this.save();
          } else {
            wx.showModal({
              title: '提示',
              content: '当前为非wifi环境下载,是否继续?',
              success: (modalres) => {
                if (modalres.confirm) {
                  this.save();
                } else {
                  wx.showToast({
                    title: '已取消下载',
                    icon: "none"
                  })
                  that.init();
                }
              }
            })
          }
        },
      })
    },
    // 根据文件的尾缀来辨别类型
    saveByType: (_path) => {
      // 视频文件
      let _pathlist = _path.split('.');
      let _type = _pathlist[_pathlist.length - 1];
      // 视频文件
      if (constant.videoType.indexOf(_type) != -1) {
        that.saveVideoLocal(_path);
      } else {
        wx.showToast({
          title: `该文件的类型为:${_type},未定义操作`,
          icon: "none"
        })
      }
    },
    // 保存视频至本地
    saveVideoLocal(_path) {
      wx.saveVideoToPhotosAlbum({
        filePath: _path,
        success() {
          wx.showToast({
            title: '保存成功!',
            icon: "none",
            duration: 2000
          })
        },
        fail: function() {
          wx.showToast({
            title: '保存失败',
            icon: "none"
          })
        },
      })
    },
    //下载之后的初始化
    init() {
      that.setData({
        initshow: false,
        progress: 0,
        showProgress: true
      });
    }

  }
})

wxml文件:

<view class="cover" wx:if='{{initshow&&initpath}}' catchtouchmove='true'>
  <view class='modal_box'>
    <view class="title">下载进度</view>
    <progress wx:if='{{showProgress}}' class="progress" percent='{{progress}}' border-radius='10' stroke-width="12" activeColor="blue"></progress>
    <view wx:if='{{showProgress}}' class="progress_info">{{progress}}%</view>
    <view wx:if='{{!showProgress}}' class="progress_info">正在下载,请稍等</view>
    <view class="operationbtn" bindtap="cancelevent">取消</view>
  </view>
</view>
.modal_box {
  width: 600rpx;
  overflow: hidden;
  position: fixed;
  top: 30%;
  left: 50%;
  z-index: 1001;
  background: #fff;
  transform: translateX(-50%) translateY(-50%);
  border-radius: 3rpx;
}

.title {
  padding: 15rpx;
  margin-top: 20rpx;
  text-align: center;
  background-color: gazure;
  color: #000;
  font-weight: bold;
}

.cover {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.3);
}

.progress {
  width: 550rpx;
  margin-left: 25rpx;
}

.operationbtn {
  width: 550rpx;
  margin-left: 25rpx;
  text-align: center;
  margin-top: 30rpx;
  border-radius: 10rpx;
  border: 1rpx solid #ccc;
  font-size: 30rpx;
  line-height: 60rpx;
  height: 60rpx;
  margin-bottom: 20rpx;
}

.progress_info {
  width: 550rpx;
  margin-left: 25rpx;
  text-align: center;
  margin-top: 30rpx;
  border-radius: 10rpx;
  font-size: 30rpx;
  line-height: 60rpx;
  height: 60rpx;
  margin-bottom: 20rpx;
}

大体是这样,

代码:https://github.com/hushilin01/public_mk_miniprogram

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值