Angular 7从POST下载PDF文件

时间:2019-01-25 11:02:01

标签: angular typescript

我正在尝试下载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文件,以便将其下载到客户端?

1 个答案:

答案 0 :(得分:1)

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

Saving binary data as file using JavaScript from a browser

因此数据应为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);