小程序展示PDF并改名

400 阅读2分钟

「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战」。

小程序展示PDF并改名

由于在uni官网没有找到直接展示pdf的方法和api,所以迫于无奈只能另想他法

思路

1. 通过uni.downloadFileapi下载文件然后拿到图片的临时路径tempPath

2. 通过uni.saveFileapi将临时路径保存到本机的文件目录中的路径filePath

3. 拿到本地路径后通过uni.openDocumentapi打开文件

下面说完思路我们就来看看代码。

async function download(path,name){
    let tempPath = await uni.downloadFile({url: path});		
    //众所周知uni中的api类似异步函数,所以在这里用await等待执行并且定义变量tempPath接收,
    let path = await uni.saveFile({
    //同理通过临时文件路径可以拿到本地真实路径,tempFilePath就是通过download下载得到的
    tempFilePath:tempPath[1].tempFilePath,
    filePath: wx.env.USER_DATA_PATH + '/' + name + '.pdf',
    //name为下方自定义的名字
    })
    let open = await uni.openDocument({
            //filePath为真实路径
            filePath: path[1].savedFilePath,
            showMenu: true, //分享的按钮
            fileType: 'pdf',
    })
    uni.showToast({
            title:`${open[1].errMsg}`,
            duration:2000
    })
}
let path = 'https:*********.pdf'
let name = '隐私政策'
download(path,name) 

tempPath拿到的数组中有临时路径

image.png

同理在filepath中拿到的真实路径就是

image.png

最后打开文档。注意,这种方式由于都会重新下载一次文件,所以在下载完文件后可以通过uni官方的缓存api做一下识别。如果没用过uni缓存的朋友,uni.setstoragesync,大家可以自行去官网进行搜索,

感谢读者大大的阅读,作为一个前端小白,写作的内容多少会有点瑕疵,如果写的文章有不好值得纠正的地方,欢迎各位读者大大们的指正和探讨。