微信小程序预览 word、excel、ppt、pdf 等文件

微信小程序预览 word、excel、ppt、pdf 等文件

预览效果

前言

微信官方提供了相关的 API 来预览常见文件,目前支持如下格式的文件

总结一下就是先用 wx.downloadFile API 把文件下载下来,再用 wx.openDocument API 把它打开

注意点

wx.downloadFile API 单次下载允许的最大文件为 200MB

需要在小程序后台配置 downloadFile 合法域名才能下载文件

实现代码

以预览 PDF 文件为例

  • 下载文件需要一个等待过程,所以加上加载提示很有必要
const util = require('../../utils/util') // 引入封装过的加载提示

Page({
    // 预览文件
    previewFile(fileLink) {
        if(!fileLink) {
            return false
        }
        util.showLoading()
      
        // 单次下载允许的最大文件为 200MB
        wx.downloadFile({
            url: fileLink, // 地址已打码,自己换个其他的地址("https://www.xxxxx.com/file/测试通知.pdf")
            success: function (res) {
                console.log(res, "wx.downloadFile success res")
                if(res.statusCode != 200) {
                    util.hideLoadingWithErrorTips()
                    return false
                }
                var Path = res.tempFilePath //返回的文件临时地址,用于后面打开本地预览所用
                wx.openDocument({
                    filePath: Path,
                    showMenu: true,
                    success: function (res) {
                        console.log('打开成功');
                        util.hideLoading()
                    }
                })
            },
            fail: function (err) {
                console.log(err, "wx.downloadFile fail err");
                util.hideLoadingWithErrorTips()
            }
        })
      
    }
})

util.js

/* 加载动画相关 */
const showLoading = (tips = '加载中...') => {
  wx.showNavigationBarLoading()
  wx.showLoading({
    title: tips,
  })
}

const hideLoading = () => {
  wx.hideLoading()
  wx.hideNavigationBarLoading()
}

const hideLoadingWithErrorTips = (err = '加载失败...') => {
  hideLoading()
  wx.showToast({
    title: err,
    icon: 'error',
    duration: 2000
  })
}

module.exports = {
  showLoading: showLoading,
  hideLoading: hideLoading,
  hideLoadingWithErrorTips: hideLoadingWithErrorTips,
}

补充

每次点击都要重新下载文件很不友好,可以考虑把文件地址存下来,如果下过了就直接打开

个人扩展思路:

第一次点击调用 wx.downloadFile 将返回的文件本地地址存到 localStorage 缓存里,每次点击前去 localStorage 里看一下有没有这条数据的本地地址,有的话就直接调用 wx.openDocument 打开,打开失败函数里判断下是不是本地文件已经清理掉了,清理掉了就重新下载再打开

原文地址:https://www.cnblogs.com/suwanbin/p/15207984.html