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

一、实现的功能:

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",
        });
      },
    });
  },
相关推荐
打小就很皮...2 小时前
HBuilder 发行Android(apk包)全流程指南
前端·javascript·微信小程序
前端缘梦13 小时前
微信小程序登录方案实践-从账号体系到用户信息存储
前端·微信小程序
coding随想16 小时前
2025年小程序开发全解析:技术储备、行业趋势与实战案例
微信小程序
Nueuis1 天前
微信小程序前端面经
前端·微信小程序·小程序
轩1151 天前
实现仿中国婚博会微信小程序
微信小程序·小程序
知否技术1 天前
2025微信小程序开发实战教程(一)
前端·微信小程序
喝牛奶的小蜜蜂1 天前
个人小程序:不懂后台,如何做数据交互
前端·微信小程序·小程序·云开发
2501_918941052 天前
旅游微信小程序制作指南
微信小程序·小程序·旅游
邹荣乐2 天前
微信小程序动态tabBar实现:基于自定义组件,灵活支持不同用户角色与超过5个tab自由组合
前端·微信小程序·uni-app
半兽先生2 天前
uniapp微信小程序视频实时流+pc端预览方案
微信小程序·uni-app·音视频