微信小程序pdf预览功能实现(解决小程序下载pdf文件后缀为unknown导致不可预览问题多种方案)

描述

因为项目是使用wepy框架开发的,所以语法上面如果大家是使用其它的方案要注意下,其实思路和核心代码大体上相同。、

思路

首先,做这个功能得知道,ios使用web-view标签是直接可以浏览pdf的,但是安卓系统的手机是不可以的,这个时候我们一般采用先下载,然后再打开的方式浏览。只要是借助小程序的wx.downloadFilewx.openDocument事件实现这个功能。然后再区分ios和安卓使用不同的方法。

上代码

页面部分

<web-view wx:if="{
     
     {iosTrue}}" src="{
     
     {src}}"></web-view>

js逻辑

  data = {
    
    
    src: "",
    iosTrue: false,
    system: "",
  };
onLoad(option) {
    
    
	//因为可能路径带参数,小程序跳转时会省略,所以我在这里做了转码
    this.src = decodeURIComponent(option.pdfId);
    this.$apply();
    this.getPhoneModel();
  }
	//判断手机系统,执行不同的方案
  getPhoneModel() {
    
    
    var that = this;
    wx.getSystemInfo({
    
    
      success: function(res) {
    
    
        console.log(res.system);
        that.system = res.system;
        var str = "iOS";
        if (that.system.indexOf(str) != -1) {
    
    
          //IOS环境
          that.iosTrue = true;
          console.log("IOS环境");
          that.$apply();
        } else {
    
    
          this.androidPdf()
          console.log("安卓环境");
        }
        that.$apply();
      }
    });
  }

  androidPdf() {
    
    
    wx.downloadFile({
    
    
      url: this.src,
      // filePath: `${wx.env.USER_DATA_PATH}/` +'xxx.pdf', // 如果你发现你下载的pdf文件后缀为unknown,导致不可预料,你可以自己定义文件名字
      success: function(res) {
    
    
        console.log(res);
        // var Path = res.filePath //自己定义的文件名,返回的时候就不是tempFilePath字段了,注意下。
        var Path = res.tempFilePath; //返回的文件临时地址,用于后面打开本地预览所用
        // that.webview=Path
        console.log(Path);
        wx.openDocument({
    
    
          // filePath: `${wx.env.USER_DATA_PATH}/` +'xxx.pdf', //当然也可以不用上面的路径,直接打开你自己定义的文件名字,但是这个前提是你前面使用的是自定义的文件名
          filePath: Path,
          fileType: "pdf", //后缀为unknown的话,可以直接以pdf的格式打开,也可以。我就是用这种,都行,反正开心就好。
          success: function(res) {
    
    
            console.log("打开文档成功");
          }
        });
      },
      fail: function(res) {
    
    
        console.log(res);
      }
    });
  }

到这里就结束了,很简单的实现。

个人水平有限,有问题欢迎大家留言指导,仅供学习和参考。

学海无涯!努力二字,共勉!

猜你喜欢

转载自blog.csdn.net/qq_37131884/article/details/104545264