微信小程序实现下载功能(以下载视频为例)

首先,采用 wx.downloadFile()方法,访问视频对应的Url,回调函数返回一个该视频文件的临时路径。
微信小程序实现下载功能(以下载视频为例)_第1张图片

 wx.downloadFile({
            url: app.serverUrl + me.data.videoInfo.videoPath,
            success: function (res) {
              // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
              if (res.statusCode === 200) {
              //打印临时路径
                console.log(res.tempFilePath);

         
              }
            }
          })

然后采用 wx.saveVideoToPhotosAlbum()方法,保存视频到系统相册,成功!
微信小程序实现下载功能(以下载视频为例)_第2张图片

       wx.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success:function(res) {
                    console.log(res.errMsg)
                    wx.hideLoading(); 
                  }
                })

完整代码如下
//downloadFile.js

wx.showLoading({
            title: '下载中...',
          })
          wx.downloadFile({
              //视频信息的Url
            url: app.serverUrl + me.data.videoInfo.videoPath,
            success: function (res) {
              // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
              if (res.statusCode === 200) {
                console.log(res.tempFilePath);

                wx.saveVideoToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success:function(res) {
                    console.log(res.errMsg)
                    wx.hideLoading(); 
                  }
                })
              }
            }
          })

你可能感兴趣的:(微信小程序,小程序)