微信小程序--实现下载预览文件并分享

需求点:使用wx.downloadFile()、wx.openDocument()两个API配合,下载预览文件并分享

问题:wx.downloadFile()的 url 参数填入的路径中带有中文,请求API时,文件路径中的中文被转码了,导致下载不了正确的文件,tempFilePath返回的是后缀.bin的文件,wx.openDocument()无法打开预览

配合使用wx.FileSystemManager()的几个API,保存重命名后可以打开预览了,解决思路如下:

// 创建存放目录
  createCatalog (e) {
    const rootPath = wx.env.USER_DATA_PATH
    const cachePath = rootPath + '/openFileCache'
    const manage = wx.getFileSystemManager()

    let newFileName = ''
    let fileType = ''
    let downLoadPath = e.currentTarget.dataset.path
    if (e.currentTarget.dataset.path.indexOf('.xlsx') !== -1) {
      fileType = '.xlsx'
    } else if (e.currentTarget.dataset.path.indexOf('.xls') !== -1) {
      fileType = '.xls'
    } else if (e.currentTarget.dataset.path.indexOf('.pdf') !== -1) {
      fileType = '.pdf'
    }
    newFileName = this.data.recordData[e.currentTarget.dataset.idx].title + fileType
    
    // 判断是否已存在自定义目录
    manage.access({
      path: cachePath,
      success: res => {
        console.log(res)
        let readdir = manage.readdirSync(cachePath)
        console.log(readdir)
        for (let path of readdir) {
          manage.unlinkSync(cachePath + '/' + path)
        }
        this.openFileEv(cachePath, newFileName, downLoadPath)
      },
      fail: err => {
        console.log(err)
        // 新建自定义目录
        manage.mkdir({
          dirPath: cachePath,
          recursive: true,
          success: res => {
            console.log('创建成功')
            this.openFileEv(cachePath, newFileName, downLoadPath)
          },
          fail: err => {
            console.log('创建失败')
          }
        })
      }
    })
  },
  // 打开文件
  openFileEv (cachePath, newFileName, downLoadPath) {
    const manage = wx.getFileSystemManager()
    wx.showLoading({
      title: '加载中',
      mask: true,
      success: function () {
        wx.downloadFile({
          // 示例 url,并非真实存在
          url: downLoadPath,
          success: function (res) {
            if (res.statusCode === 200) {
              wx.hideLoading()
              manage.saveFileSync(res.tempFilePath, cachePath + '/' + newFileName)
              // 打开文档
              wx.openDocument({
                filePath: cachePath + '/' + newFileName,
                showMenu: true,
                success: function (res) {
                  console.log('打开文档成功')
                },
                fail: function () {
                  console.log('打开失败')
                }
              })
            }
          }
        })
      }
    })
  }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值