• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
茶茶呀
帮助1

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

学新通

需求

在线预览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() {},
      });
    },
学新通

最后

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfihji
系列文章
更多 icon
同类精品
更多 icon
继续加载