下载文件“带有下载名称的发送文件”

时间:2018-09-20 16:00:32

标签: javascript angular asp.net-core .net-core rxjs

我有一个Angular 6应用程序,我想从我的.NET Core API下载生成的PDF。

每个调用似乎都有效,但是我不确定如何下载/打开文件。

  

Microsoft.AspNetCore.Mvc.Infrastructure.FileContentResultExecutor:信息:   执行Microsoft.AspNetCore.Mvc.FileContentResult,发送文件   下载名称为“ test.pdf” ...

Reporting API:

public IActionResult CreateReport()
{
  XtraReport report = m_ReportingManager.GetReport();

  MemoryStream ms = new MemoryStream();
  report.ExportToPdf(ms);

  HttpContext.Response.ContentType = "application/pdf";
  FileContentResult result = new FileContentResult(ms.GetBuffer(), "application/pdf")
  {
    FileDownloadName = "test.pdf"
  };

  return result;
}

在Angular组件中,我有2个对服务的调用(SO中有1个,我自己有1个)

public getReport1() {
    this._reportViewerService.getReport()
      .subscribe(blob => {
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = "test.pdf";
        link.click();
      }, error => { console.log(error) });
  }

  public getReport2() {   
    this._reportViewerService.getReport().subscribe(
      (result: any) => window.open("http://localhost:44302/Reporting/test.pdf", "_blank"),
      (error: any) => this._loggerService.logError(error),
      () => this.loading = false
    );
  }

我的服务如下:

  public getReport(definitionKey: string, reportParameters: ReportParameter[]): Observable<any> {
    const parameters = {
      key: definitionKey,
      reportParameters: reportParameters
    };

    return this._http.post<any>(this.baseUrl + 'CreateReport', parameters);
  }

1 个答案:

答案 0 :(得分:0)

您可以使用File Saver包来处理文件下载。

https://www.npmjs.com/package/file-saver

我是在我的应用程序中这样做的,希望您可以将其调整为适合您的应用程序

downloadFile(data: Response){
  let blob = new Blob([data], { type: 'application/pdf' });
  let url= window.URL.createObjectURL(blob);
  console.log(url);
  window.open(url);
}

getPdf() {
   const options: {
        headers?: HttpHeaders,
        observe?: 'body',
        params?: HttpParams,
        reportProgress?: boolean,
        responseType: 'blob',
        withCredentials?: boolean
    } = {
        headers: null,
        params: null,
        responseType: 'blob'
    };

this.http.get(`your api endpoint`, options)
  .subscribe(blob => {
    saveAs(blob, 'file.pdf');
  });
 }