微信小程序预览 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,
}
  • 12
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RealizeInnerSelf丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值