小程序附件下载并预览功能

一、实现的功能:

1、word、excel、图片等实现下载并预览

2、打开文件后显示文件名称

二、代码:

javascript 复制代码
// 判断文件类型
  whatFileType(url) {
    let sr = url.lastIndexOf("."); //  最后一次出现的位置
    let fileType = url.substr(sr + 1); // 截取url的类型
    return fileType;
  },

  // 下载文件
  /**
   * 本地文件存储的大小限制为 10M
   */
  handleDownloadFile(e) {
    let fileTypes = ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"];
    let imageTypes = ["jpg", "jpeg", "png"];
    let fileType = this.whatFileType(e.target.dataset.fileurl);
    let fileName = imageTypes.includes(fileType) ? "" : e.target.dataset.name;
    const timestamp = Date.parse(new Date());
    wx.showLoading({
      title: "加载中",
    });
    wx.getSavedFileList({
      // 获取文件列表
      success(res) {
        res.fileList.forEach((val, key) => {
          // 遍历文件列表里的数据
          // 删除存储的垃圾数据
          wx.removeSavedFile({
            filePath: val.filePath,
          });
        });
      },
    });
    wx.downloadFile({
      url: e.target.dataset.fileurl,
      filePath: fileTypes.includes(fileType)
        ? wx.env.USER_DATA_PATH + "/" + timestamp + fileName
        : wx.env.USER_DATA_PATH + "/" + "." + fileType,
      method: "GET",
      success: function (res) {
        if (fileTypes.includes(fileType)) {
          wx.openDocument({
            filePath: res.filePath,
            showMenu: true,
            flieType: fileType,
            success: function (res) {
              wx.hideLoading();
            },
            fail: function (err) {
              wx.hideLoading();
            },
          });
        } else if (imageTypes.includes(fileType)) {
          wx.hideLoading();
          wx.previewImage({
            showmenu: true,
            current: res.filePath, // 当前显示图片的http链接
            urls: [res.filePath], // 需要预览的图片http链接列表
          });
        } else {
          wx.hideLoading();
          wx.showModal({
            title: "提示",
            content: "文件类型不支持预览",
            showCancel: false,
          });
        }
      },
      fail: function (err) {
        wx.hideLoading();
        wx.showToast({
          title: "下载超时",
          icon: "none",
        });
      },
    });
  },
相关推荐
云起SAAS17 小时前
供求求购供应发布VIP会员抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·供求求购供应发布
毕设源码-朱学姐17 小时前
【开题答辩全过程】以 基于微信小程序旅游疫情防控管理系统为例,包含答辩的问题和答案
微信小程序·小程序·旅游
一点晖光19 小时前
ios底部按钮被挡住
前端·ios·微信小程序
前端程序猿之路1 天前
基于扣子(Coze)工作流 API 的微信小程序开发实践总结
前端·微信小程序·小程序·大模型·api·ai编程·扣子
德育处主任1 天前
在小程序做海报的话,Painter就很给力
前端·微信小程序·canvas
丸子哥哥2 天前
vue + uni-app:利用原生uni.chooseImage封装拍照功能的组件
微信小程序·uni-app·vue
计算机毕设指导62 天前
基于微信小程序的旅游线路定制系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·旅游
qq_12498707532 天前
基于Spring Boot的微信小程序的智慧商场系统的设计与实现
java·spring boot·spring·微信小程序·小程序·毕业设计·计算机毕业设计
2503_928411562 天前
12.26 小程序代码片段【添加WeaUI内容】
前端·微信小程序·小程序
计算机毕设指导62 天前
基于微信小程序的博物馆文创系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea