调用浏览器的api实现word,Excel,pdf等预览

export function previewOrDownload(options: { originUrl: string; type?: string; data?: any }) {
  const { originUrl, type = 'download' } = options;
  if (type === 'preview') {
    const lastIndex = originUrl.lastIndexOf('.');
    const suffix = originUrl.substring(lastIndex + 1);
    //文件格式是word文档、ppt、excel文件文件时
    if (['doc', 'docx', 'ppt', 'xls', 'xlsx'].includes(suffix)) {
      const encodedUrl = encodeURIComponent(window.$SYS_CFG.apiServiceFileURL + originUrl); // 编码完整的URL
      // 使用 Office Web 查看器
      const officeUrl = `http://view.officeapps.live.com/op/view.aspx?src=${encodedUrl}`;
      window.open(officeUrl, '_blank'); // 在新标签页中打开预览
    } else {
      //其他文件格式比如pdf、图片、html
      window.open(window.$SYS_CFG.apiServiceFileURL + originUrl);
    }
  } else if (type === 'download') {
    // -------xhr 下载--------
    const xhr = new XMLHttpRequest();
    xhr.open('GET', window.$SYS_CFG.apiServiceFileURL + originUrl);
    xhr.responseType = 'blob'; // 设置响应类型为二进制数据
    xhr.onload = function () {
      if (xhr.status === 200) {
        const blob = new Blob([xhr.response], {
          type: 'application/octet-stream',
        });
        const index = originUrl.lastIndexOf('/');
        const filename = originUrl.substring(index + 1, originUrl.length);
        const anchor = document.createElement('a');
        const downloadUrl = URL.createObjectURL(blob);
        anchor.href = downloadUrl;
        anchor.download = filename;
        anchor.click();
        URL.revokeObjectURL(downloadUrl); // 释放URL对象
      }
    };
    xhr.send();
  }
}

你可能感兴趣的:(word,excel,pdf,javascript)