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

时间:2021-09-01 23:15:09   收藏:0   阅读:28

微信小程序预览 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,
}

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

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!