uniapp的文件预览

743 阅读1分钟

uniapp的文件预览

    uniapp开发中我们经常会遇到文件预览的问题,本文将小程序开发中所有可能遇到的文件类型进行了汇总,希望在开发中可以给予你们帮助。


步骤

1. 获取文件后缀

举例:文件名 url = "something.png" -> url.lastIndexOf('.')==>.slice(index + 1)
得到文件后缀 *png*

2. 根据文件类型调用微信提供的方法

获得后缀名判断类型,如果是图片:wx.previewImage(),如果是视频:wx.previewMedia()如果是word文档这些的,用 wx.downloadFile来下载资源后用 wx.saveFile来保存到本地,再用wx.openDocument来打开新的网页,如果打不开的话则提示到PC端去打开

附上代码

if (['bmp', 'jpg', 'jpeg', 'png', 'gif', 'image'].some(item => item == filttype)) {
      wx.previewImage({
        current: "http:******" + url, // 当前显示图片的 http 链接
        urls: ["http:******" + url], // 需要预览的图片 http 链接列表
        success() {
          wx.hideLoading()
        }
      })
    } else if (['mp4'].some(item => item == filttype)) {
      wx.previewMedia({
        sources: [{
          url: "http:******" + 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: "http:******" + url,
        // 从后端获取的url地址,赋值在标签的data属性上
        header: {
          "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
        },
        success: function (res) {
          const tempFilePath = res.tempFilePath;
          //  return
          wx.saveFile({ //保存文件到本地
            tempFilePath,
            success(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: '下载失败',
          })
        }
      })
    }

上述代码即可解决日常开发中遇到的所有文件预览的类型处理。