下載並預覽文檔:
1.通過 downloadFile方法,下載成功,
2.然后接着調用openDocument打開文檔
openDocument新開頁面打開文檔,支持合法格式:DOC, XLS, PPT, PDF, DOCX, XLSX, PPTX。
小程序文檔:https://developers.weixin.qq.com/miniprogram/dev/api/wx.openDocument.html
這里模擬列表數據查看文檔。
<block wx:for="{{list}}" > <view class='background'> <view data-url="{{item.url}}" catchtap='downloadFile' class='color'>{{item.title}}</view> <view> <text class='times'>上傳時間:</text> <text>{{item.time}}</text> </view> </view> </block>
Page({ /** * 頁面的初始數據 */ data: { list:[ { title:'前端學習正品', url:'http://*************.pdf', time:"2019.1.10" }, { title: '小程序最全項目', url: 'http://***************.pdf', time: "2019.1.10" } ] }, /** * 生命周期函數--監聽頁面加載 */ onLoad: function (options) { var that = this; }, /** * 下載文件並預覽 */ downloadFile: function (e) { let url = e.currentTarget.dataset.url; console.log("*********正在獲取文件名****" + url) wx.downloadFile({ url: url,//這里的url是通過模擬數據里面的數組對象,列表形式方式 //url:"http://*************.pdf", //這樣的固定文檔值, success: function (res) { const filePath = res.tempFilePath; //返回的文件臨時地址,用於后面打開本地預覽所用 console.log("文件"+filePath); wx.openDocument({ filePath: filePath, success: function (res) { console.log('您成功打開文檔,歡迎閱讀') }, fail: function (res) { console.log(res); console.log("錯誤") }, }) }, fail: function (res) { console.log('文件下載失敗'); }, }) }, })
這樣就完成了在線閱讀文檔