最近做小程序,涉及到教育培训的模块,需求web端上传的课件,在小程序端可以进行预览。
在微信小程序开发,对预览文件的格式是有限制的。
课件的预览主要用到的是,小程序的下载和打开。
1.下载方法 wx.downloadFile(Object object)
wx.downloadFile({
url: 'https://example.com/audio/123', //仅为示例,并非真实的资源
success:function (res) {
const filePath = res.tempFilePath
// 下载成功后的操作
},
fail: function (params) {
wx.showToast({
title: '文件下载失败',
icon: 'none',
duration: 2000
})
}
// 个人觉得fail这个回调函数最好写上,因为如果不写,下载失败了,都不会有提醒,写上至少知道程序执行到哪一步了,问题出在哪里
})
这里用了wx.showToast()做提示,只是有一点不是很明白,它的icon表示了类型,为什么用success和error都会是√这个成功的标志呢???(求解!!!)
2.文件类型的预览 wx.openDocument(Object object)
wx.openDocument({
filePath: filePath,
showMenu: true,
fileType: fileType,
success: function (res) {
console.log('打开文档成功')
},
fail: function (params) {
// console.log(params)
wx.showToast({
title: '文件类型不支持',
icon: 'none',
duration: 2000
})
}
})
这里的filePath就是,上面下载方法wx.downloadFile()获得的 filePath
支持打开的文件类型是以下几种。避免出现打不开的情况,fileType最好能写上。在拿到文件列表的时候,肯定会有存在后台的名字,用split('.')进行切割,取[1],就可以得到文件后缀,即fileType。fileType = fileName.split('.')[1],如果不支持就提示“不支持该文件类型!”
3. 图片预览 wx.previewImage(Object object, boolean showmenu)
这个方法很简单,只有两行,放进去就好了。
// 这是官网给的
wx.previewImage({
current: '', // 当前显示图片的http链接
urls: [] // 需要预览的图片http链接列表
})
// 我们拿来用
wx.previewImage({
current: filePath, // 这是我们下载方法得到的图片路径
urls: imgList // 这是列表,多个图片用的
})
值得注意的是:一张图片,urls也是必须要写的,将filePath,push到imgList就可以了。
4.视频播放 <video>
这个视频播放,我写的比较简单,只要可以播放就可以了。
视频播放支持的一些格式:
下面是wxml文件
<view style="text-align: center">
<video src="{{videoFile}}" id="Video" show-mute-btn bindfullscreenchange="bindFullScreenChange"></video>
</view>
让videoFile = filePath即可。bindFullScreenChange()这个是全屏方法。
this.videoContext.requestFullScreen() 进入全屏
this.VideoContext.exitFullScreen() 退出全屏
其他方法,可参考微信小程序开发手册。https://developers.weixin.qq.com/miniprogram/dev/api/media/video/VideoContext.html
总结:2.3.4都是写在wx.downloadFile(Object object)都是写在的success中的,即先下载文件,再进行打开查看或者播放。
最后提供一下文件查看和图片查看的相对完整点的代码。视频播放的也是类似的。
let fileType = event.currentTarget.dataset.raw.filename.split('.')[1]
wx.downloadFile({
// 示例 url,并非真实存在
url: url, // 这就是后台提供的下载预览文件的地址
success: function (res) {
const filePath = res.tempFilePath
if (fileType==='jpg'||fileType==='png') { // 这边我只打开jpg和png格式哈,可根据需要自行调整
const imgList = []
imgList.push(filePath)
wx.previewImage({
current: filePath, // 当前显示图片的http链接
urls: imgList // 需要预览的图片http链接列表
})
}else{
wx.openDocument({
filePath: filePath,
showMenu: true,
fileType: fileType,
success: function (res) {
console.log('打开文档成功')
},
fail: function (params) {
// console.log(params)
wx.showToast({
title: '文件类型不支持',
icon: 'none',
duration: 2000
})
}
})
}
},
fail: function (params) {
// console.log(params)
wx.showToast({
title: '文件下载失败',
icon: 'none',
duration: 2000
})
}
})
效果图:
文档是在电脑中打开的,就不截图了,亲测有效。