小程序中打开pdf文件(wx.downloadFile+wx.openDocument)

wx.downloadFile({}) 下载,然后 用 wx.openDocument({}) 打开文件

1、先请求到 pdf 路径网络地址,将 pdf 下载到本地

2、从本地文件上传到一个临时路径中,将本地文件删除

3、打开临时路径的文件

注意:需要在开发者管理中,配置一下downloadFile合法域名:

        微信公众平台-->开发管理-->开发设置-->downloadFile合法域名

openHandle() {
    let that = this;
    const fileExtName = ".pdf";
    const randfile = new Date().getTime() + fileExtName;
    const newPath = `${wx.env.USER_DATA_PATH}/${randfile}`;  // 定义一个临时路径
    that.deletContract();  // 将本地文件删除
    wx.downloadFile({
      url: "", // 网络文件的地址
      header: {
        "content-type": "application/pdf",
        Authorization: wx.getStorageSync("token"),
      },
      filePath: newPath,
      success: function (res) {
        const filePath = res.tempFilePath;
        wx.openDocument({
          filePath: newPath,
          showMenu: true,
          fileType: "pdf",
          success: function (res) {},
        });
      },
      fail: function (res) {
        wx.hideLoading();
      },
    });
  },
  // 删除本地文件
  deletContract() {
    try {
      let file = wx.getFileSystemManager();
      file.readdir({
        dirPath: `${wx.env.USER_DATA_PATH}`,
        success: (res) => {
          if (res.files.length > 2) {
            file.unlink({
              filePath: `${wx.env.USER_DATA_PATH}/${res.files[0]}`,
              complete: (res) => {},
            });
          }
        },
      });
    } catch (error) {}
  },

猜你喜欢

转载自blog.csdn.net/LXY_1999/article/details/128012155