1. 使用微信小程序提供的api(注意顺序,先下载,在打开)
- wx.downloadFile下载资源到本地(临时文件,退出即销毁)
- filePath:
${wx.env.USER_DATA_PATH}/${fileName}.${extName} // 指定下载后存储路径(处理打开后的文件名乱码问题)
- wx.openDocument新页面打开文档
- showMenu 是否显示右上角菜单按钮,可实现右上角分享
export default function useFilePreview() {
const getFileNameAndExtName = (
filePath: string
): {
fileName: string
extName: string
} => {
const fileNameWithExt: string = filePath.split('/').pop() || ''
const fileName = fileNameWithExt.split('.').slice(0, -1).join('.')
const extName: string = fileNameWithExt.split('.').pop() || ''
return {
fileName,
extName,
}
}
const previewFile = (url: string) => {
uni.showLoading({
title: '加载中...',
})
const { fileName, extName } = getFileNameAndExtName(url)
uni.downloadFile({
url,
filePath: `${wx.env.USER_DATA_PATH}/${fileName}.${extName}`,
success: (res: any) => {
if (res.statusCode === 200) {
uni.openDocument({
showMenu: true,
filePath: res.filePath,
fileType: extName,
success: (rest) => {
console.log(rest, '文件打开成功')
},
fail: (err) => {
uni.showToast({
title: '文件打开失败请重试',
icon: 'none',
})
},
})
} else {
uni.showToast({
title: '文件下载失败',
icon: 'none',
})
}
},
fail: (err) => {
uni.showToast({
title: '文件下载失败',
icon: 'none',
})
},
complete: () => {
uni.hideLoading()
},
})
}
return {
getFileNameAndExtName,
previewFile,
}
}