微信小程序查看附件

微信小程序查看附件

通过判断使用wx.previewImage来查看图片, 
wx.previewMedia来查看视频
 wx.downloadFile+wx.saveFile+ wx.openDocument来查看文档,例如word 、pdf
 使用看一下详情
  //查看附件详情
  lookfile(e) {
    const url = e.currentTarget.dataset.url;
    // 获得后缀名判断类型,如果是图片用ex.previewImage(),如果是视频,用wx.previewMedia(),如果是word文档这些的,用 wx.downloadFile来下载资源后用 wx.saveFile来保存到本地,在用wx.openDocument来打开新的网页,如果打不开的话则返回说到PC端去打开
    let index = url.lastIndexOf('.')
    let filttype = url.slice(index + 1)
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    if (['bmp', 'jpg', 'jpeg', 'png', 'gif', 'image'].some(item => item == filttype)) {
      wx.previewImage({
        current: url, // 当前显示图片的 http 链接
        urls: [url], // 需要预览的图片 http 链接列表
        success() {
          wx.hideLoading()
        }
      })
    } else if (['mp4'].some(item => item == filttype)) {
      // console.log(url)
      wx.previewMedia({
        sources: [
         {
          url: e.currentTarget.dataset.url,
          type: 'video'
         }
        ], // 需要预览的资源列表
        current: 1, // 当前显示的资源序号,
        success(){
          wx.hideLoading()
        }
      })
    } else if (['zip', 'rar'].some(item => item == filttype)) {
      wx.showToast({
        title: '不好意思,暂不支持预览,请到pc端查看',
        icon:"none"
      })
    } else {
      wx.downloadFile({ //下载
        url: e.currentTarget.dataset.url, // 从后端获取的url地址,赋值在标签的data属性上
        header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        success: function (res) {
          console.log(res)
          const tempFilePath = res.tempFilePath;
          //  return
          wx.saveFile({ //保存文件到本地
            tempFilePath,
            success(res) {
              console.log(res)
              const savedFilePath = res.savedFilePath;
              wx.openDocument({ //新开页面打开文档
                filePath: savedFilePath,
                showMenu: true,
                flieType: filttype,
                success: function (res) {
                  wx.hideLoading()
                  console.log('打开文档成功')
                },
                fail: function (err) {
                  wx.hideLoading()
                  wx.showToast({
                    title: '不好意思,暂不支持预览,请到pc端查看',
                    icon:"none"
                  })
                }
              });
            },
          })
        },
        fail: function (err) {
          wx.showToast({
            title: '下载失败',
          })
          console.log(err)
        }
      })
    }


  },
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值