代码之家  ›  专栏  ›  技术社区  ›  ItFreak

Angular 7从Post下载PDF文件

  •  1
  • ItFreak  · 技术社区  · 6 年前

    我正在尝试下载一个发布请求返回的PDF文件:
    这是我的角度法:

      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[] 把它下载到客户机上?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Nguyen Phong Thien    6 年前

    您可以使用从日志中获得的数据并创建,然后按照此解决方案创建可下载的文件。

    Saving binary data as file using JavaScript from a browser

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

    在typescript中应该是

    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);