微信小程序打开pdf文件,并支持保存分享等操作

发布时间 2023-04-13 14:16:31作者: ZerlinM

微信小程序直接下载文件时,保存到的路径为缓存路径 tempxxx,如果需要查找文件就很麻烦,那我们可以先在小程序中预览文件,再执行后续操作,代码如下:

// 方法
const download = (type) => {
    const { url = '', name } = type;
    if (!url) return;
    console.log('uuuu', url, name)
    Taro.showLoading({
      title: '加载文件中'
    })
    Taro.downloadFile({//下载文件
      // url,
      url: 'http://www.shidz.gov.cn/download.jsp?pathfile=/atm/7/20230330114133316.xlsx',//需要下载的文件流
      filePath: Taro.env.USER_DATA_PATH + '/' + name + '.xlsx',
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('下载成功')
          // this.saveFile(res.filePath);// 如果不自定义文件下载路径又需要永久保存走这步,其他小程序不能用此路径 Taro.env.USER_DATA_PATH ,可以参照uniapp文档
          Taro.hideLoading();
          Taro.openDocument({
            filePath: res.filePath,
            showMenu: true, // 右上角显示三个点,微信自带的api,可以保存、转发文件
            success: function (res) {
              console.log('打开文档成功');
            }
          });
        } else {
          Taro.hideLoading();
          Taro.showToast({
            title: '加载失败'
          });
        }
      }
    });
  }

// 使用
download({
  url: '文件路径',
  name: '文件名称'
})

附:

微信官方api