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

一、实现的功能:

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",
        });
      },
    });
  },
相关推荐
小蒜学长6 小时前
基于springboot 校园餐厅预约点餐微信小程序的设计与实现(代码+数据库+LW)
数据库·spring boot·微信小程序
cookqq6 小时前
Cursor和Hbuilder用5分钟开发微信小程序
微信小程序·小程序·curosor
毕设源码-钟学长8 小时前
【开题答辩全过程】以 基于微信小程序的美发服务系统的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
canglingyue9 小时前
微信小程序罗盘功能开发指南
微信小程序·小程序
三脚猫的喵12 小时前
微信小程序中实现AI对话、生成3D图像并使用xr-frame演示
前端·javascript·ai作画·微信小程序
海绵宝宝不喜欢侬13 小时前
UniApp微信小程序-实现蓝牙功能
微信小程序·uni-app
Python大数据分析16 小时前
uniapp微信小程序商品列表数据分页+本地缓存+下拉刷新+图片懒加载
缓存·微信小程序·uni-app
小白_ysf16 小时前
uniapp和vue3项目中引入echarts 、lime-echart(微信小程序、H5等)
微信小程序·uni-app·echarts·h5·lime-echart
imHere·16 小时前
UniApp 分包异步化配置及组件引用解决方案
微信小程序·uni-app·分包
canglingyue18 小时前
微信小程序加速计开发指南
微信小程序·小程序