最近做了个需求是在微信小程序中下载 pdf 文件并可直接预览,我们是用uniapp 进行的开发,一些实现在此记录一下。
1. 下载后端返回的url文件
uni.downloadFile({
url: res.report_url
success: (success) => {
uniSaveFile(success.tempFilePath);
}
})
通过 downloadFile 会得到一个临时地址
2. 将临时地址保存到手机
saveFile 官方文档
openDocument 官方文档
wx.env.USER_DATA_PATH: 微信小程序中用于存储用户数据的路径,可以读取或写入数据
const uniSaveFile = (tempPath: string) => {
wx.getFileSystemManager().saveFile({
tempFilePath: tempPath
filePath: `${wx.env.USER_DATA_PATH}/${reportDetailData.value.title}.pdf`, // 重命名
success: (res) => {
setTimeout(()=>{
uni.openDocument({
filePath: res.savedFilePath,
showMenu: true,
fileType: 'pdf',
success: (success) => {}
})
}, 1000)
}
fail: (fail) => {
console.log(fail)
}
})
}