首先,wxml代码:
<b bindtap="openfile" data-type="jpg" data-src="https://www.sy-dq.com/1.pdf">下载文件<i class="fa fa-download">i>b>
绑定js函数,并注意 type 和 src参数。
然后,js函数openfile如下:
//打开文件函数 openfile: function (e) { var ftype = e.currentTarget.dataset.type; //获取文件类型 var fsrc = e.currentTarget.dataset.src; //获取文件地址 if (fsrc == "") { wx.showToast({ title: '文件地址错误', icon: 'none', mask: true, duration: 2000 }) return false; } // 检查文件格式是否不正确 let fileIndex = fsrc.lastIndexOf('.') let substrName = fsrc.substr(fileIndex) let formatImg = /.(doc|docx|xls|xlsx|ppt|pptx|pdf|jpg|png|gif|jpeg)$/i // 定义正则 // 验证格式 if(!formatImg.test(substrName)){ wx.showToast({ title: '不支持的文件格式', icon: 'none', mask: true, duration: 2000 }) return false; } wx.downloadFile({ url: fsrc, success: function (res) { const filePath = res.tempFilePath; console.log('本地文件地址:'+filePath); wx.openDocument({ filePath: filePath, success: function (res) { console.log('打开文档成功') } }) } }) }