微信小程序的文件預覽需要先使用wx.downloadFile下載文件,然后使用下載文件的臨時路徑通過wx.openDocument進行文件的預覽
項目中,有的需要打開pdf 來閱讀信息。就需要用小程序自帶的api方法。
wxml代碼:
<button bindtap='preview'>PDF文件預覽</button>
js代碼:
//PDF預覽 preview: function () { var that = this; console.log("PDF預覽") //這里的value是先在data里面初始化,然后我根據用戶切換單選框,獲取的PDF文件的主鍵id console.log(this.data.value) var id = that.data.value; if (id == "") { wx.showModal({ title: '', content: '請選擇一份PDF', showCancel: false, confirmColor: "#FFB100" }) } else { //先通過PDF的主鍵id,查詢PDF路徑(大家可以根據自己的需求來傳數據) wx.request({ url: app.globalData.url + "/api/interview/queryFilePath", data: { id: id }, method: 'POST', header: { "content-type": "application/x-www-form-urlencoded" }, success: function (res) { console.log(res.data) that.setData({ path: res.data.path, type: res.data.type }) //下載PDF wx.downloadFile({ url: app.globalData.url + that.data.path, success: function (res) { var filePath = res.tempFilePath console.log(filePath) //預覽PDF wx.openDocument({ filePath: filePath, fileType: that.data.type, success: function (res) { console.log("打開文檔成功") console.log(res); }, fail: function (res) { console.log("fail"); console.log(res) }, complete: function (res) { console.log("complete"); console.log(res) } }) }, fail: function (res) { console.log('fail') console.log(res) }, complete: function (res) { console.log('complete') console.log(res) } }) } }) } },