Skip to content

在小程序中查看文件处理

统一处理,无法识别的文件类型使用文档尝试打开

js
const toViewFile = (fileUrl) => {

  // 图片
  if (isImageUrl(fileUrl)) {
    wx.previewImage({
      urls: [fileUrl],
      current: fileUrl,
      fail: function () {
        wx.showToast({ title: '预览图片失败', icon: 'none' });
      },
    });
    return false;
  }
  // 视频
  if (isVideoUrl(fileUrl)) {
    wx.previewMedia({
      sources: [
        {
          url: fileUrl,
          type: 'video',
        },
      ],
      current: 0,
      fail: function () {
        wx.showToast({ title: '预览视频失败', icon: 'none' });
      },
    });
    return false;
  }
  wx.showLoading({
    title: '下载中...',
  });
  // 其他
  wx.downloadFile({
    url: fileUrl,
    success: (res) => {
      wx.hideLoading({
        success: (res) => {},
      });
      // 其他
      wx.openDocument({
        filePath: res.tempFilePath,
        showMenu: true,
        fail() {
          wx.showToast({
            title: '查看失败!',
            icon: 'none',
          });
        },
      });
    },
    fail(err) {
      console.log(err);
      wx.hideLoading({
        success: (res) => {},
      });
      wx.showToast({
        title: '下载失败!',
        icon: 'none',
      });
    },
  });
};