開發小程序遇到這樣的一個問題,客戶需要預覽pdf文件,直接上代碼
wx.showLoading({ title: '加載中', mask: true }) wx.downloadFile({ url: 'http://xxx.pdf', // 預覽pdf文件地址 success: function(res) { wx.hideLoading() const tempFilePath= res.tempFilePath; wx.showLoading({ title: '正在打開', mask: true }) wx.openDocument({ filePath: tempFilePath, fileType: 'pdf', success: function(res) { uni.hideLoading() }, fail: function(err) { uni.hideLoading() } }); }, fail: function(err) { wx.hideLoading() } });
但是這樣出現了一個問題,那就是文件的名稱是微信直接定義的,用戶不知道是什么項目的pdf文件,因此需要自定義打開pdf文件的名稱,上代碼:
wx.showLoading({ title: '加載中', mask: true }) wx.downloadFile({ url: 'http://xxx.pdf', // 預覽pdf文件地址 filePath: wx.env.USER_DATA_PATH + '/' + '自定義文件名稱.pdf', // 需要預覽文件的名稱 success: function(res) { wx.hideLoading() const filePath= res.filePath; // 這個地方也是關鍵 wx.showLoading({ title: '正在打開', mask: true }) wx.openDocument({ filePath: filePath, fileType: 'pdf', success: function(res) { uni.hideLoading() }, fail: function(err) { uni.hideLoading() } }); }, fail: function(err) { wx.hideLoading() } });
這樣就可以預覽的文件名稱就改變了。