如何使用文件保护程序在 Angular 中下载 Excel 文件

How to Download Excel file in Angular using File Saver

我在 PHP 中创建了 post 表单,点击按钮时它正在下载一个 excel 文件,我也有一些表单数据 posted 到URL 和文件用于通过纯 HTML 成功下载并提交表单

在 PHP 中,这是将表单 post 编辑到文件时触发的函数

public function downloadExcel($fileName = '', $addTimeStamp = true) {
    $fileName = (!$fileName) ? 'excel_download' : preg_replace('/\s+/', '_', $fileName);
    if ($addTimeStamp) {
        $fileName .= date('_d_m_Y_H_i_s');
    }
    $fileName .= '.xlsx';
    $this->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="' . $fileName . '"');
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
    header('Cache-Control: cache, must-revalidate');
    header('Pragma: public');
    $objWriter = PHPExcel_IOFactory::createWriter($this, 'Excel2007');
    $objWriter->save('php://output');
}

当它工作时,我在请求中设置了以下内容 Headers

响应中没有显示任何内容

但现在我们正在尝试将前端迁移到我们能够从中下载文件的 Angular 框架,我已经尝试过他的方法

downloadTheExport() {
  this.downloadfile().subscribe((blob: any) => {
    const blobdownload = new Blob([blob], { type: "application/vnd.ms-excel;charset=utf-8" });
    saveAs(blobdownload, 'testdata.xls');
  });
}

downloadfile(){
  const formDataForExport: FormData = new FormData();
  formDataForExport.append('export', 'ALL');

  return this.http.post('http://localhost:8080/service/exportExcel.php', formDataForExport, {
    headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' }
  });
}

并且当我尝试在 Angular 中下载它时,我观察到当在 Angular 中进行调用时,Content-Type 的请求 header 似乎已更改Content-Type: multipart/form-data; boundary angular 并且当我在响应选项卡中看到它显示如下数据时。

你能帮我在Angular这种情况

下如何实现下载吗

您的 请求 header 中的 Content-Type 是正确的,因为您确实 post 通过 php 后端的 formDataForExport .

但是处理响应的方式似乎不对。我提出以下解决方案可能会有所帮助:

假设您正在引用此 fileSaver:

https://github.com/Hipparch/file-saver-typescript/blob/master/file-saver.ts

建议包含以上脚本并使用它,因为要处理保存文件时的不同浏览器行为,它很复杂并且不适合 re-implement 它们。

downloadTheExport() {
  this.downloadfile().subscribe((resp: any) => {
    const fileSaver: any = new FileSaver();
    fileSaver.responseData = resp.body;
    fileSaver.strFileName = 'testdata.xls';
    fileSaver.strMimeType = 'application/vnd.ms-excel;charset=utf-8';
    fileSaver.initSaveFile();
  });
}

downloadfile() {
  const formDataForExport: FormData = new FormData();
  formDataForExport.append('export', 'ALL');

  return this.http.post('http://localhost:8080/service/exportExcel.php', formDataForExport, {
    headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9' },
    responseType: 'blob',
    observe: 'response'
  });
}