微信小程序打开PDF、word等文件预览

        近期在使用uniapp开发微信小程序时,碰到了要在小程序上打开PDF文件预览的需求,使用原生微信小程序开发的实现和这个也是类似的。实现大致代码如下:

// 下载文件到本地,下载成功后会返回临时文件路径
uni.downloadFile({
    url: "文件地址",
    success: function (res) {
        let filePath = res.tempFilePath;   // 下载成功后返回的临时文件路径

        // 打开临时文件
        uni.openDocument({
            filePath: filePath,
            showMenu: true,
            success: function (res) {
                console.log('打开文档成功');
            }
        });
    },
    fail: (err) => {
        // 处理下载失败的情况
    }
});

        这里主要用到了两个API:uni.downloadFile( ) 和 uni.openDocument( ),这两个API的功能如下:

  1. uni.downloadFile( ):发起请求,将资源下载到本地,请求成功后返回文件的本地临时路径,临时路径仅在本次启动期间可用,若需持久保存,需在主动调用 uni.saveFile ,才能在应用下次启动时访问得到,在微信小程序上使用,需要配置白名单。官网API使用文档:uni.uploadFile(OBJECT) | uni-app官网
  2. uni.openDocument( ):新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx。官网API使用文档:uni.saveFile(OBJECT) @savefile | uni-app官网

猜你喜欢

转载自blog.csdn.net/m0_60312580/article/details/131322499
今日推荐