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

一、实现的功能:

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",
        });
      },
    });
  },
相关推荐
TiAmo zhang2 小时前
微信小程序开发案例 | 极简清单小程序(下)
微信小程序·小程序·notepad++
從南走到北3 小时前
JAVA国际版同城外卖跑腿团购到店跑腿多合一APP系统源码支持Android+IOS+H5
android·java·ios·微信小程序·小程序
码起来呗15 小时前
基于微信小程序的旅游攻略分享互动平台设计与实现-项目分享
微信小程序·小程序·旅游
郑叔敲代码17 小时前
帝国cms微信小程序 微信授权登录api接口
微信小程序·帝国cms小程序·帝国cms开发
dcloud_jibinbin18 小时前
【uniapp】小程序体积优化,分包异步化
前端·vue.js·webpack·性能优化·微信小程序·uni-app
wapchief1 天前
微信小程序camera相机帧转图片base64
微信小程序·小程序
QuantumLeap丶1 天前
《uni-app跨平台开发完全指南》- 05 - 基础组件使用
vue.js·微信小程序·uni-app
泽_浪里白条1 天前
UniApp + Vue3 开发微信小程序数字人:TTS PCM 音频流与 SVGA 动画同步实战
微信小程序
小蒜学长1 天前
springboot基于Java的校园导航微信小程序的设计与实现(代码+数据库+LW)
java·spring boot·后端·微信小程序
WenGyyyL1 天前
微信小程序开发——第二章:微信小程序开发环境搭建
开发语言·python·微信小程序