微信小程序预览二进制流文件

开发时使用调试基准库版本

在这里插入图片描述

需求

在线预览doc/xls/xlsx/ppt/txt/pdf 的文件和图片。

思路

  1. 将后台返回的二进制流,写入微信的文件管理器。
  2. 打开文件。

根据文件类型调用不同预览方法

wx.openDoucument不支持预览txt文件。

    bindTapFile: function (e) {
      let currentPage = this;
      let { objectId, name, filetype } = e.currentTarget.dataset.file;
      let fileType = name.split(".").pop().toLowerCase();
      if (
        ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"].includes(fileType)
      ) {
        currentPage.binaryPreview(objectId, name, filetype);
      } else if (["txt"].includes(fileType)) {
        currentPage.downloadFilePreview(objectId, name, filetype, true);
      }
    },

原本写的预览方法,安卓不支持

原本都是调用这个方法,根据isTxt判断是否为文本文件做不同的操作。在安卓真机调试发现打开失败,说找不到路径。

    downloadFilePreview: function (objectId, name, type, isTxt = false) {
      let currentPage = this;
      let filePath = `${wx.env.USER_DATA_PATH}/${name}`;
      ui.showLoading("加载中……");
      wx.downloadFile({
        url: `${app.globalData.loscamUrl}...`,
        filePath: filePath, // 自定义文件的名称
        method: "GET",
        header: {
          Authorization: "Bearer " + token.access_token,
        },
        success(res) {
          let Path = res.filePath;
          let fs = wx.getFileSystemManager();
          fs.getFileInfo({
            filePath: Path,
            success: (f) => {
              fs.saveFile({
                tempFilePath: Path ?? filePath,
                filePath: filePath,
              });
              if (isTxt) {
                let textContent = fs.readFileSync(filePath, "utf-8");
                currentPage.goTxtPage(name, textContent);
              } else {
                // 现api支持doc docx xls xlsx ppt pptx pdf
                wx.openDocument({
                  filePath: Path ?? filePath,
                  showMenu: true,
                  fileType: type,
                  success: function (res) {
                    console.log("打开文档成功");
                  },
                  fail: function (err) {
                    console.log("打开文档失败:", err);
                  },
                });
              }
            },
          });
        },
        complete() {
          setTimeout(() => {
            ui.hideLoading();
          }, 1000);
        },
      });
    },

苹果、安卓真机均可预览文件

    binaryPreview: function (objectId, name, type) {
      let filePath = `${wx.env.USER_DATA_PATH}/${name}`;
      ui.showLoading("加载中……");
      wx.request({
        url: `${app.globalData.loscamUrl}...`,
        header: {
          Authorization: "Bearer " + token.access_token,
        },
        method: "GET",
        responseType: "arraybuffer", //此处是请求文件流,必须带入的属性
        success: (rest) => {
          if (rest.statusCode === 200) {
            const fs = wx.getFileSystemManager(); //获取全局唯一的文件管理器
            fs.writeFile({
              // 写文件
              filePath: filePath,
              data: rest.data,
              encoding: "binary",
              success(res) {
                wx.openDocument({
                  filePath: filePath, //拿上面存入的文件路径
                  showMenu: true,
                  success: function (res) {
                    console.log("open success");
                  },
                  fail: function (err) {
                    console.log("open fail", err);
                  },
                });
              },
            });
          }
        },
        complete() {
          setTimeout(() => {
            ui.hideLoading();
          }, 1000);
        },
      });
    },

预览图片

缩略图预览(增加请求头部)

效果图
在这里插入图片描述
代码实现

    downloadImgToTemUrl(imgObjectId, imgName) {
      let currentPage = this;
      wx.downloadFile({
        url: `${app.globalData.loscamUrl}/file/downloadfile?fileUrl=${imgObjectId}`,
        filePath: `${wx.env.USER_DATA_PATH}/${encodeURIComponent(imgName)}`, // 自定义文件的名称
        method: "GET",
        header: {
          Authorization: "Bearer " + currentPage.data.access_token,
        },
        success(res) {
          let path = wx
            .getFileSystemManager()
            .readFileSync(res.filePath, "base64");
          currentPage.properties.fileList.forEach((x, i) => {
            if (imgObjectId == x.objectId) {
              currentPage.setData({
                ["fileList[" + i + "].imgToTemUrl"]: `data:image/jpg;base64,${path}`,
              });
            }
          });
        },
        complete() {},
      });
    },

点击缩略图预览图片

效果图
在这里插入图片描述

代码实现
注意点:路径含有中文的图片预览不了。
改正:将图片的名字改为全英文字符就可以了。

    bindImgPreview: function (e) {
      let { name, idx } = e.currentTarget.dataset;
      let currentIndex = -1;
      let currentPage = this;
      let urls = currentPage.data.urls;
      urls.forEach((x, i) => {
        if (x == `${wx.env.USER_DATA_PATH}/${name}`) {
          currentIndex = i;
          return;
        }
      });
      wx.previewImage({
        current: urls[currentIndex],
        urls: urls,
        success(res) {
          console.log("预览成功");
        },
        fail(err) {
          console.log("预览失败,原因:", err);
        },
        complete() {},
      });
    },

最后

如果你有更好的办法可以相互交流,共同进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茶茶呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值