微信小程序中预览文件问题

413 阅读1分钟

1. 使用微信小程序提供的api(注意顺序,先下载,在打开)

  • wx.downloadFile下载资源到本地(临时文件,退出即销毁)
    • filePath: ${wx.env.USER_DATA_PATH}/${fileName}.${extName} // 指定下载后存储路径(处理打开后的文件名乱码问题)
  • wx.openDocument新页面打开文档
    • showMenu 是否显示右上角菜单按钮,可实现右上角分享
/**
 * 微信小程序预览附件(word/excel/ppt/pdf)
 */
export default function useFilePreview() {
  // 获取文件名和后缀名
  const getFileNameAndExtName = (
    filePath: string
  ): {
    fileName: string
    extName: string
  } => {
    const fileNameWithExt: string = filePath.split('/').pop() || '' // 处理路径分隔符
    const fileName = fileNameWithExt.split('.').slice(0, -1).join('.') // 获取文件名(不包括后缀)

    // 获取后缀名
    const extName: string = fileNameWithExt.split('.').pop() || '' // 获取后缀名

    return {
      fileName,
      extName,
    }
  }

  const previewFile = (url: string) => {
    uni.showLoading({
      title: '加载中...',
    })
    const { fileName, extName } = getFileNameAndExtName(url)
    uni.downloadFile({
      url,
      // uni.env.USER_DATA_PATH:返回小程序本地用户文件目录
      filePath: `${wx.env.USER_DATA_PATH}/${fileName}.${extName}`, // 指定下载后存储路径(处理打开后的文件名乱码问题)
      success: (res: any) => {
        if (res.statusCode === 200) {
          uni.openDocument({
            showMenu: true,
            filePath: res.filePath,
            fileType: extName, // 坑:fileType可选,但是不指定的话,文件会打不开
            success: (rest) => {
              console.log(rest, '文件打开成功')
            },
            fail: (err) => {
              uni.showToast({
                title: '文件打开失败请重试',
                icon: 'none',
              })
            },
          })
        } else {
          uni.showToast({
            title: '文件下载失败',
            icon: 'none',
          })
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '文件下载失败',
          icon: 'none',
        })
      },
      complete: () => {
        uni.hideLoading()
      },
    })
  }

  return {
    getFileNameAndExtName,
    previewFile,
  }
}