前言
我們經常需要打開各種文檔,無論是學習還是工作中,電子書一大把,怎麼在小程序上打開閱讀呢? 學小程序,找豬哥就對了。
js核心代碼:
* 下載文件並預覽
*/
readPdf(e){
console.log(e); // 接收傳入的下載地址參數
let type = e.currentTarget.dataset.type; 下載類型
let url = e.currentTarget.dataset.url; 下載地址
console.log('下載地址',url)
wx.downloadFile({ // 開始下載文件
url: url,
header: {},
success: function (res) { 下載成功之後執行
var filePath = res.tempFilePath;
console.log('下載成功',filePath);
wx.openDocument({ // 打開預覽下載成功的文件
filePath: filePath,
success: function (res) {
console.log('打開文檔成功')
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
console.log(res);
}
})
},
fail: function (res) {
console.log('文件下載失敗');
},
complete: function (res) { },
})
},
效果
總結
這裏調用了微信小程序的兩個接口:
1.wx.downloadFile
2.wx.openDocument
關鍵是要傳遞對文件下載地址,並且需要在後臺添加request域名,域名記得備案。
閱讀完有問題?聯繫我,加微信:ichatme002