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

一、实现的功能:

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",
        });
      },
    });
  },
相关推荐
咸虾米_4 小时前
微信小程序通过uni.chooseLocation打开地图选择位置,相关设置及可能出现的问题
微信小程序·小程序·uniapp开发·小程序地图api
不如摸鱼去1 天前
Trae 辅助下的 uni-app 跨端小程序工程化开发实践分享
微信小程序·小程序·uni-app·aigc·ai编程
意会1 天前
微信闪照小程序实现
前端·css·微信小程序
小白_ysf1 天前
uniapp 开发微信小程序,获取经纬度并且转化详细地址(单独封装版本)
微信小程序·uni-app
是一碗螺丝粉2 天前
拯救你的app/小程序审核!一套完美避开审核封禁的URL黑名单机制
前端·javascript·微信小程序
我叫黑大帅2 天前
微信小程序分包:告别加载慢,像拆快递一样简单!
前端·微信小程序
两个月菜鸟3 天前
vue+微信小程序 五角星
前端·vue.js·微信小程序
熬耶3 天前
Uniapp之微信小程序自定义底部导航栏形态
微信小程序·小程序·uni-app
誰在花里胡哨4 天前
微信小程序实现陀螺仪卡片景深效果
前端·微信小程序·动效
XXXFIRE4 天前
微信小程序开发实战笔记:全流程梳理
前端·微信小程序