微信小程序下载 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()
          }
        }
      })
    }
},

相关推荐

  1. 程序下载 base64 视频文件本地相册

    2023-12-13 06:36:03       40 阅读
  2. uniapp程序下载保存图片流本地,base64

    2023-12-13 06:36:03       46 阅读
  3. uniapp程序下载base64图片流或https图片

    2023-12-13 06:36:03       38 阅读
  4. 程序实现图片转base64

    2023-12-13 06:36:03       10 阅读
  5. 程序下载文件详解

    2023-12-13 06:36:03       9 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-13 06:36:03       14 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-13 06:36:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-13 06:36:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-13 06:36:03       18 阅读

热门阅读

  1. kafka学习笔记--节点的服役与退役

    2023-12-13 06:36:03       45 阅读
  2. 小程序猎鹰策略组件

    2023-12-13 06:36:03       37 阅读
  3. 《C++新经典设计模式》之第2章 模板方法模式

    2023-12-13 06:36:03       33 阅读
  4. Spark SQL 的partitionBy() 动态分区

    2023-12-13 06:36:03       34 阅读