首页 > 解决方案 > Angular 7 从 POST 下载 PDF 文件

问题描述

我正在尝试下载 POST 请求返回的 PDF 文件:
这是我的 Angular 方法:

  sendPost: void {
  const options = {headers: {'Content-Type': 'application/json'}};
    this.http.post('http://localhost:8080/export', JSON.stringify(this.filter), 
    options )
      .subscribe((next) => console.log(next));
  }

以及生成 PDF 的 Java 后端:

@CrossOrigin
@RequestMapping(value = "/export/", method = RequestMethod.POST)
public ResponseEntity<byte[]> getFilteredPDF(@RequestBody PdfExportFilter filter) throws IOException, DocumentException {
    StructureExporter writer = new FilteredPdfExporter(filter);
    Path filePath = Paths.get(writer.getBaseTempDir() + "/filteredExport.pdf");
    writer.exportData();
    return new ResponseEntity<byte[]>(readPdfBytes(filePath), getHttpHeaders("_filtered_export"), HttpStatus.OK);
}

如何将返回的内容保存byte[]为 PDF 文件以便下载到客户端?

标签: angulartypescript

解决方案


您可以使用从帖子中获得的数据并创建,并按照此解决方案创建可下载的文件

使用浏览器中的 JavaScript 将二进制数据保存为文件

所以数据应该是next来自console.log(next)

在打字稿中应该是

const a = document.createElement('a');
document.body.appendChild(a);
a.style.display = 'none';

const blob = new Blob(next, {type: "octet/stream"}),
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);

推荐阅读