У меня есть приложение Angular 6, и я хочу загрузить сгенерированный PDF файл из моего.NET Core API.
Каждый из вызовов кажется действительным, но я не уверен, как загрузить/открыть файл.
Microsoft.AspNetCore.Mvc.Infrastructure.FileContentResultExecutor: Информация: Выполнение Microsoft.AspNetCore.Mvc.FileContentResult, отправка файла с именем загрузки 'test.pdf'...
API Reporting
:
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;
}
И в моем Угловом компоненте у меня есть 2 обращения к службе (1 из SO и 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);
}
Вы можете использовать пакет 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');
});
}
{ responseType: 'blob' }
вашемthis._http.post<any>(this.baseUrl + 'CreateReport', parameters);
это должно бытьthis._http.post<any>(this.baseUrl + 'CreateReport', parameters,{ responseType: 'blob' });