首页 > 解决方案 > Angular 5 - Node/Express - 无法下载 pdf

问题描述

我正在尝试从本地文件夹下载 pdf 文件,该文件夹的结构类似于 assets/test.pdf。

服务器.js

app.get('/ePoint', (req,res)=>{
 // some dumb code :P
});

演示.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Headers } from '@angular/http';
import {Observable} from 'rxjs'; 
fileDownload() {
    const headers = new HttpHeaders();
    headers.append('Accept', 'application/pdf');
    this._http.get('http://localhost:3000/ePoint',  { headers: headers })
      .toPromise()
      .then(response => this.saveItToClient(response));
  }
    private saveItToClient(response: any) {
    const contentDispositionHeader: string = response.headers.get('Content-Disposition');
    const parts: string[] = contentDispositionHeader.split(';');
    const filename = parts[1].split('=')[1];
    const blob = new Blob([response._body], { type: 'application/pdf' });
    saveAs(blob, filename);
  }

我不知道我在哪里做错了。在浏览器网络控制台中。它的显示 200 好。但在普通浏览器控制台中显示如下附件

在此处输入图像描述 在此处输入图像描述

注意:我从这里提到了 ts 文件

非常感谢

标签: node.jsangularexpress

解决方案


尝试这个...

组件.ts

downloadDocument(documentId: string) {
    this.downloadDocumentSubscription = this.getService.downloadScannedDocument(documentId).subscribe(
      data => {
        this.createImageFromBlob(data);
      },
      error => {
        console.log("no image found");
        $("#errorModal").modal('show'); //show download err modal
      });
  }

  createImageFromBlob(image: Blob) {
    console.log("mylog", image);
    if (window.navigator.msSaveOrOpenBlob) // IE10+
      window.navigator.msSaveOrOpenBlob(image, "download." + (image.type.substr(image.type.lastIndexOf('/') + 1)));
    else {
      var url = window.URL.createObjectURL(image);
      window.open(url);
    }
  }

服务.ts

downloadScannedDocument(documentId: string): Observable<any> {

    let params = new HttpParams();
    if (documentTypeParam == false)
        params = params.set('onlyActive', 'false');
    let fileResult: Observable<any> = this.http.get(`${this.apiBaseUrl}/${documentId}`, { responseType: "blob", params: params });
    return fileResult;
}

推荐阅读