微信小程式預覽 word、excel、ppt、pdf 等檔案
阿新 • • 發佈:2021-08-30
目錄
微信小程式預覽 word、excel、ppt、pdf 等檔案
預覽效果
前言
微信官方提供了相關的 API 來預覽常見檔案,目前支援如下格式的檔案
總結一下就是先用 wx.downloadFile
API 把檔案下載下來,再用 wx.openDocument
API 把它開啟
- wx.downloadFile:下載檔案到本地
- wx.openDocument:新開頁面開啟本地文件
注意點
wx.downloadFile API 單次下載允許的最大檔案為 200MB
-
網路-使用說明(域名只支援
https
wss
(wx.connectSocket) 協議) -
可以結合 DownloadTask 相關 API 實現下載進度展示
需要在小程式後臺配置 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, }