从api调用获取文件路径字符串后自动下载PDF

时间:2019-03-08 19:57:56

标签: node.js angular typescript

我有此代码段,返回的字符串是pdf文件的路径。我想知道,我不只是返回字符串,而是可以在调用后自动在浏览器中下载pdf吗?如果是这样,怎么办?

getMergedPDF(filesToUpload: Array<string>) {
    return this.http.post<string>('http://localhost:8080/merge-pdf', filesToUpload)
    .subscribe(data  => this.mergedUrl = data);
  }

上面返回的字符串是文件路径:/Users/foo/Documents/PDFMerger/PDFMerger/server/test-pdfs/merged-pdf.pdf

编辑:当我尝试以下解决方案时,文件无法加载。

2 个答案:

答案 0 :(得分:1)

您会有类似的内容

.subscribe(data  => {
  var dl = document.createElement('a');
  dl.setAttribute('href', data);
  dl.setAttribute('download', 'pdfname.pdf');
  document.body.appendChild(dl);
  dl.click();
  document.body.removeChild(dl);
});

答案 1 :(得分:0)

您可以尝试以下操作:

            getMergedPDF(filesToUpload: Array<string>) {
    return this.http.post<string>('http://localhost:8080/merge-pdf', filesToUpload)
    .subscribe(data  => {
             this.mergedUrl = data;
             this.getPDF(this.mergedUrl);});
getPDF(uri){
this.http.get(uri, { responseType: 'blob' }) .subscribe(x=>{

            var newBlob = new Blob([x], { type: "application/pdf" });

           //IE Fix
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(newBlob);
                return;
            }
            const data = window.URL.createObjectURL(newBlob);
            var link = document.createElement('a');
            link.href = data;
            link.download = "merge.pdf";
            link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));

            setTimeout(function () {
                window.URL.revokeObjectURL(data);
                link.remove();
            }, 100);
        });