微信小程序下载 base64 视频文件到本地相册

微信小程序下载 base64 视频文件到本地相册

问题描述:

后端传过来一个视频的 base64 编码,前端通过一个按钮点击来下载视频到本地相册。

解决代码:

// 点击下载按钮对应的方法
async uploadVideo() {
    uni.showLoading({
      title: '正在下载,请稍后...',
      mask: false
    });
    const getVideoUrl = await new Promise((resolve) => {
      // this.baseCode 为 视频编码
      // 注意的是这里的编码不需要携带 data:video/mp4;base64 前缀
      // 如果携带了,在调用writeFileSync会报 writeFileSync:fail base64 encode error
      const base64Video = this.baseCode.replace(/[\r\n]/g, '')
      // 进行本地临时存储
      const fs = uni.getFileSystemManager();
      const filePath = `${wx.env.USER_DATA_PATH}/video${new Date().getTime()}.mp4`;
      fs.writeFileSync(filePath, base64Video, 'base64');
      this.videoUrl = filePath
      resolve(true)
    })
    if (getVideoUrl) {
      wx.getSetting({
        withSubscriptions: true,
        success: res => {
          // 判断是否有相册的写入权限
          if (res.authSetting['scope.writePhotosAlbum']) {
            // 写入文件
            uni.saveVideoToPhotosAlbum({
              filePath: this.videoUrl,
              success: () => {
                uni.hideLoading()
                uni.showToast({
                  title: '保存成功,请到相册查看!',
                  icon: 'success',
                });
              },
              fail: (error) => {
                uni.hideLoading()
                uni.showToast({
                  title: '保存失败',
                  icon: 'none',
                });
                console.error('保存视频失败:', error);
              },
            });
          } else {
            // 没有权限,调用开启权限的方法,这里省略。
            uni.hideLoading()
            this.openSaveSetting()
          }
        }
      })
    }
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值