微信小程序下载视频文件wx.downloadFile下载资源失败

官方示例代码:

wx.downloadFile({
  url: 'https://example.com/audio/123', //仅为示例,并非真实的资源
  success (res) {
    // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
    if (res.statusCode === 200) {
      wx.playVoice({
        filePath: res.tempFilePath
      })
    }
  }
})

下面是完整版代码(ps:添加是否授权开启相册)

let fileName = new Date().valueOf();
wx.downloadFile({
	url: url, //下载链接
	filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
	success: res => {
		console.log(res)
		let filePath = res.filePath;
		wx.saveVideoToPhotosAlbum({
			filePath,
			success: file => {
				wx.showToast({title: '下载成功',icon: 'success',duration: 2000})
			},
			fail: err => {
				this.loading =  false
				if (err.errMsg === 'saveVideoToPhotosAlbum:fail auth deny') {
					wx.showModal({
						title: '提示',
						content: '需要您授权保存相册',
						showCancel: false,
						success: data => {
							wx.openSetting({
								success(settingdata) {
									if (settingdata.authSetting['scope.writePhotosAlbum']) {
										wx.showModal({
											title: '提示',
											content: '获取权限成功,再次点击下载即可保存',
											showCancel: false,
										})
									} else {
										wx.showModal({
											title: '提示',
											content: '获取权限失败,将无法保存到相册哦~',
											showCancel: false,
										})
									}
								},
							})
						}
					})
				}
			}
		})
	},
	fail:res=>{
		this.loading =  false
		console.log(res)
	}
})

当然,这并还没有结束
当你下载多的时候,可能会报出saveFile:fail the maximum size of the file storage limi或者uploadFile:fail exceed max upload connection count 10错误
原因是微信的使用限制
在这里插入图片描述
对于以上错误,可用FileSystemManager.readdirFileSystemManager.unlink去处理
代码如下,具体参数及回调可以查看官方文档

//读取目录内文件列表
wx.getFileSystemManager().readdir({
	dirPath: wx.env.USER_DATA_PATH,
	success(res){
		console.log(res)
	},
	fail(res){
		console.log(res)
	}
})
//删除文件
wx.getFileSystemManager().unlink({
	filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.mp4',
	success(res){
		console.log(res)
	},
	fail(res){
		console.log(res)
	}
})
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你好!机器人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值