自学内容网 自学内容网

微信小程序中的文件查看方法

获得后缀名判断类型,如果是图片用ex.previewImage(),如果是视频,用uni.previewMedia(),如果是word文档这些的,用 uni.downloadFile来下载资源后用 uni.saveFile来保存到本地,uni.openDocument来打开新的网页,如果打不开的话则返回说到PC端去打开

 const lookFile = (url) => {
  let index = url.lastIndexOf('.');
  let filttype = url.slice(index + 1);
  if (url.includes('?token')) {
    filttype = url.split('?token')[0].split('.').slice(-1);
  }
  uni.showLoading({
    title: '加载中',
    mask: true,
  });
  if (['bmp', 'jpg', 'jpeg', 'png', 'gif', 'image'].some((item) => item == filttype)) {
    uni.previewImage({
      current: url, // 当前显示图片的 http 链接
      urls: [url], // 需要预览的图片 http 链接列表
      success() {
        uni.hideLoading();
      },
    });
  } else if (['mp4', 'avi'].some((item) => item == filttype)) {
    uni.previewMedia({
      sources: [
        {
          url,
          type: 'video',
        },
      ], // 需要预览的资源列表
      current: 1, // 当前显示的资源序号,
      success() {
        uni.hideLoading();
      },
      fail: function (err) {
        uni.showToast({
          title: '播放失败',
          icon: 'none',
        });
        console.log(err);
      },
    });
  } else if (['zip', 'rar'].some((item) => item == filttype)) {
    uni.showToast({
      title: '暂不支持预览',
      icon: 'none',
    });
  } else {
    uni.downloadFile({
      //下载
      url, // 从后端获取的url地址,赋值在标签的data属性上
      header: {
        token: uni.getStorageSync('token'),
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
      success: function (res) {
        const tempFilePath = res.tempFilePath;
        uni.openDocument({
          //新开页面打开文档
          filePath: tempFilePath,
          showMenu: true,
          fileType: filttype,
          success: function (res) {
            console.log('打开文档成功');
          },
          fail: function (err) {
            console.log('打开文档失败', err);
          },
          complete: () => {
            uni.hideLoading();
          },
        });
        /* uni.saveFile({
          //保存文件到本地
          tempFilePath,
          success(res) {
            const savedFilePath = res.savedFilePath;
            const filttypeName = filttype;
            uni.openDocument({
              //新开页面打开文档
              filePath: savedFilePath,
              showMenu: true,
              fileType: filttypeName,
              success: function (res) {
                console.log('打开文档成功');
              },
              fail: function (err) {
                console.log('打开文档失败', err);
              },
              complete: () => {
                uni.hideLoading();
              },
            });
          },
        }); */
      },
      fail: function (err) {
        uni.showToast({
          title: '下载失败',
          icon: 'none',
        });
        console.log(err);
      },
    });
  }
};

原文地址:https://blog.csdn.net/bobringtheboys/article/details/142936106

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!