首页 > 技术知识 > 小程序开发 XIYCMS内容管理系统

微信小程序下载并打开文件

作者:admin 更新:2022-09-29 20:29:34 来源:XIYCMS 人气:56

首先,wxml代码:

20220929/9d0851a183d16dff889b9e4969b1a94e.png

<b bindtap="openfiledata-type="jpgdata-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('打开文档成功')
          }
        })
      }
    })
  }


你觉得这篇文章怎么样?

0 0



评论

发表