官网:
wx.openDocument(Object object) | 微信开放文档微信开发者平台文档https://developers.weixin.qq.com/miniprogram/dev/api/file/wx.openDocument.html
说的fileType是可选参数!
但是不加上的话,就打不开!
加上之后就能打开了。
关键代码:
wx.openDocument({filePath: filePath,fileType: fileType,showMenu: true,success: function(res) {console.log('打开文档成功');},fail: function(error) {wx.showToast({icon: 'none',title: '打开文件失败'});},});
测试数据:先从文件的url里面筛选文件格式:
let ss='https://www.baidu.com/f85284da55164de2a2d9cb0b62fabab1.pdf?response-content-disposition=attachment%3Bfilename%3D%E6%9D%A8%E5%AD%90%E5%B9%BF%E5%91%8A%E5%87%BA%E8%B4%A7%E5%8D%95.pdf&AWSAccessKeyId=XIDM2OFRLLDUR8YFJJWM&Expires=1679793304&Signature=WcNl5HmwWOvNU%2F51f%2F5ZQ1h9BbA%3D'ss.substring(ss.lastIndexOf(".")+1).split('&')[0]'pdf'
demo:
downloadFile(url) {url='https://www.baidu.com/f85284da55164de2a2d9cb0b62fabab1.pdf?response-content-disposition=attachment%3Bfilename%3D%E6%9D%A8%E5%AD%90%E5%B9%BF%E5%91%8A%E5%87%BA%E8%B4%A7%E5%8D%95.pdf&AWSAccessKeyId=XIDM2OFRLLDUR8YFJJWM&Expires=1679793304&Signature=WcNl5HmwWOvNU%2F51f%2F5ZQ1h9BbA%3D'console.log('url', '---的值是?', url)const sufInx = url.lastIndexOf(".");if (sufInx === -1) {uni.showModal({title: '提示信息',content: '文件错误!',success: function(res) {if (res.confirm) {//console.log('用户点击确定');} else if (res.cancel) {//console.log('用户点击取消');}}});return false}let fileType = ''console.log('sufInx', '---的值是?', sufInx)fileType = url.substring(sufInx + 1).split('&')[0]console.log('fileType', '---的值是?', fileType)let fileTypeArr = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']console.log('fileType', '---的值是?', fileType)if (!fileTypeArr.includes(fileType)) {uni.showModal({title: '提示信息',content: '只能打开word/excel/ppt/pdf文件(比如:doc, docx, xls, xlsx, ppt, pptx, pdf这些类型的文件)!',success: function(res) {if (res.confirm) {//console.log('用户点击确定');} else if (res.cancel) {//console.log('用户点击取消');}}});return false} else {wx.downloadFile({url: url, //仅为示例,并非真实的资源success: (res) => {if (res.statusCode === 200) {console.log('下载成功--res', res);var filePath = res.tempFilePath;wx.openDocument({filePath: filePath,fileType: fileType,showMenu: true,success: function(res) {console.log('打开文档成功');},fail: function(error) {wx.showToast({icon: 'none',title: '打开文件失败'});},});}},fail: function(err) {console.log('fail')console.log(err)wx.showToast({icon: 'none',title: '下载文件失败'});}});}},
最后,pdf打开成功:
来源地址:https://blog.csdn.net/qq_22182989/article/details/129438264