打开并查看pdf
const that = this
const randFile = new Date().getTime() + '.pdf' // 设置需要存储的地址
wx.downloadFile({
url: that.data.filePath, // 后端请求url下载地址
// 使用自定义目录(文件路径)进行下载/保存 需要设置的地址
filePath: `${wx.env.USER_DATA_PATH}/${randFile}`,
success(res) {
wx.openDocument({
// 注意 : 文件地址是 filePath
filePath: res.filePath,
showMenu: true,
fileType: 'pdf',
success() {
console.log("打开文档成功")
}
})
}
})
使用自定义目录进行保存下载查看的原因是在于 showMenu: true 查看文档时,进行分享,当前分享的后缀会丢失,只会获取地址 (这个地址是文件下载地址,不是文件查看文件), 分享给其他人时,是无法正常打开此文件
分享pdf文件
const randFile = new Date().getTime() + '.pdf'
wx.downloadFile({
url: this.data.filePath,
filePath: `${wx.env.USER_DATA_PATH}/${randFile}`,
success(res) {
wx.shareFileMessage({
filePath: res.filePath
})
}
})
总结
下载地址 url 如果直接是 .pdf 结尾的文件,不需要下载可直接查看pdf文档,可以直接使用微信小程序官网提供的方法,如果像是我这次遇到的,下载连接 url 只是一个下载链接,需要进行转换一下,避坑 ,避坑 ,避坑!!!!!!!!