微信小程序预览pdf文件自定义文件名称

开发小程序遇到这样的一个问题,客户需要预览pdf文件,直接上代码

wx.showLoading({
    title: '加载中',
    mask: true
})
wx.downloadFile({
    url: 'http://xxx.pdf', // 预览pdf文件地址 
    success: function(res) {
        wx.hideLoading()
        const tempFilePath= res.tempFilePath;
        wx.showLoading({
            title: '正在打开',
          mask: true
      })
      wx.openDocument({
          filePath: tempFilePath,
          fileType: 'pdf',
          success: function(res) {
            uni.hideLoading()
          },
          fail: function(err) {
            uni.hideLoading()
          }
      });
    },
    fail: function(err) {
      wx.hideLoading()
    }
});        

但是这样出现了一个问题,那就是文件的名称是微信直接定义的,用户不知道是什么项目的pdf文件,因此需要自定义打开pdf文件的名称,上代码:

wx.showLoading({
    title: '加载中',
    mask: true
})
wx.downloadFile({
    url: 'http://xxx.pdf', // 预览pdf文件地址 
    filePath: wx.env.USER_DATA_PATH + '/' + '自定义文件名称.pdf', // 需要预览文件的名称
    success: function(res) {
        wx.hideLoading()
        const filePath= res.filePath; // 这个地方也是关键
        wx.showLoading({
            title: '正在打开',
            mask: true
        })
        wx.openDocument({
            filePath: filePath,
            fileType: 'pdf',
            success: function(res) {
              uni.hideLoading()
            },
            fail: function(err) {
              uni.hideLoading()
            }
        });
    },
    fail: function(err) {
      wx.hideLoading()
    }
});

这样就可以预览的文件名称就改变了。

posted @ 2021-12-22 15:59  zaijinyang  阅读(1631)  评论(0编辑  收藏  举报