技术项目,文件的导出和pdf预览

121 阅读1分钟

"docx-preview": "^0.1.16",

// 单个导出(doc,docx,pdf预览)
const exportFile = async (item: any) => {
  // 当前用户是否有权限
  if (state.levelObj.explevel !== "1") {
    return;
  }
  // 三个格式预览
  if (item.file_type === "docx") {
    window.open(
      "/#/preview" + "?file=" + item.file_id + "&name=" + item.file_name
    );
  } else {
    downloadFileById({ id: item.file_id }).then((res) => {
      downloadFile(res.data, item.file_name, item.file_type, item.file_id);
    });
  }
};

// 批量导出下载
const exportFileAll = async (row: any) => {
  let url =
    window.location.origin +
    `/techAssess/sysFile/downloadFileByBusinessId?businessId=${row.id}`;
  getExportFile(url);
};



// 下载和pdf预览
export function downloadFile(
  fileStream: string,
  fileNames: string,
  fileFormat: string,
  fileId: string
): void {
  let applicationType = { type: 'application/vnd.ms-excel' };
  if (fileFormat === 'pdf' || fileFormat === 'doc') {
    applicationType = { type: 'application/pdf' };
  }
  const blob = new Blob([fileStream], applicationType);
  if ('download' in document.createElement('a')) {
    // 非IE下载
    const elink = document.createElement('a');
    // elink.download = fileNameS
    elink.setAttribute('download', fileNames + '.' + fileFormat);
    elink.style.display = 'none';
    elink.href = URL.createObjectURL(blob);
    document.body.appendChild(elink);
    // pdf 预览
    if (fileFormat === 'pdf') {
      window.open('/#/preview' + '?url=' + URL.createObjectURL(blob));
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else if (fileFormat === 'doc') {
      // 获取文件目录地址
      previewDocAndPdf(fileId).then(res => {
        // console.log(res);
        if (res.data.data) {
          window.open(`${process.env.VUE_APP_FILE_URL}/${res.data.data}`);
        }
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      });
    } else {
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    }
  } else {
    // IE10+下载
    // navigator.msSaveBlob(blob, fileName)
  }
}


// get请求url点击直接下载-本人简单方法
export const getExportFile = (url: string) => {
  const link = document.createElement("a"); // 创建一个 a 标签用来模拟点击事件
  link.style.display = "none";
  link.href = url;
  link.setAttribute("download", "文件名");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};


/**
 * 下载接口
 * @param params 
 * @returns 
 */
export function downloadFileById(params: { id: string }): AxiosPromise<any> {
  return request({
    url: 'sysFile/downloadFileById',
    method: 'GET',
    responseType: 'blob',
    params
  });
}

// 获取文件下载地址目录接口
// `
export function previewDocAndPdf(id: string): AxiosPromise<SuccessInfo<any>> {
  return request({
    url: `sysFile/previewDocAndPdf?fileId=${id}`,
    method: 'GET'
  });
}