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

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

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

预览效果

前言

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

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

注意点

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

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

实现代码

以预览 PDF 文件为例

  • 下载文件需要一个等待过程,所以加上加载提示很有必要
  1. const util = require('../../utils/util') // 引入封装过的加载提示
  2. Page({
  3. // 预览文件
  4. previewFile(fileLink) {
  5. if(!fileLink) {
  6. return false
  7. }
  8. util.showLoading()
  9. // 单次下载允许的最大文件为 200MB
  10. wx.downloadFile({
  11. url: fileLink, // 地址已打码,自己换个其他的地址("https://www.xxxxx.com/file/测试通知.pdf")
  12. success: function (res) {
  13. console.log(res, "wx.downloadFile success res")
  14. if(res.statusCode != 200) {
  15. util.hideLoadingWithErrorTips()
  16. return false
  17. }
  18. var Path = res.tempFilePath //返回的文件临时地址,用于后面打开本地预览所用
  19. wx.openDocument({
  20. filePath: Path,
  21. showMenu: true,
  22. success: function (res) {
  23. console.log('打开成功');
  24. util.hideLoading()
  25. }
  26. })
  27. },
  28. fail: function (err) {
  29. console.log(err, "wx.downloadFile fail err");
  30. util.hideLoadingWithErrorTips()
  31. }
  32. })
  33. }
  34. })

util.js

  1. const showLoading = (tips = '加载中...') => {
  2. wx.showNavigationBarLoading()
  3. wx.showLoading({
  4. title: tips,
  5. })
  6. }
  7. const hideLoading = () => {
  8. wx.hideLoading()
  9. wx.hideNavigationBarLoading()
  10. }
  11. const hideLoadingWithErrorTips = (err = '加载失败...') => {
  12. hideLoading()
  13. wx.showToast({
  14. title: err,
  15. icon: 'error',
  16. duration: 2000
  17. })
  18. }
  19. module.exports = {
  20. showLoading: showLoading,
  21. hideLoading: hideLoading,
  22. hideLoadingWithErrorTips: hideLoadingWithErrorTips,
  23. }
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。