通过Angular保存已创建的PDF或CSV文件(不导出)

时间:2018-10-25 09:06:40

标签: java angular file io

我有两个端点

POST `reports/pdf`
{
payload
}

并且:

POST `reports/csv`
{
payload
}

返回临时文件为 file:///C:/Users/UserFolder/AppData/Local/Temp/csv6677594787854925068.csvfile:///C:/Users/UserFolder/AppData/Local/Temp/pdf6677594753424925068.pdf

我使用这种方法创建服务来获取该文件:

exportReport(summaryCustomerReport: SummaryCustomerReport): Observable<Object> {
const exportUrl = `${this.reportsUrl}/pdf`;


return this.http.post(exportUrl, summaryCustomerReport);
}
private get reportsUrl() {
return `${environment.backendUrl}/reports`;
}

然后我尝试使用该服务:

downloadPdf() {
this.hoursWorkedForCustomersService.exportReport(this.summaryCustomerReport, ExportFileFormat[ExportFileFormat.PDF]).subscribe(
  result => {
    saveAs(result, 'new.pdf');
   },
  error => { console.error(error) },
  () => {}
);}

但是我有一个错误

Access to XMLHttpRequest at 'file:///C:/Users/UserFolder/AppData/Local/Temp/csv6677594787854925068.csv' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

还有:

ERROR DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///C:/Users/UserFolder/AppData/Local/Temp/csv6677594787854925068.csv'.

我尝试使用类似问题的解决方案,例如使用chrome.exe --allow-file-access-from-files --disable-web-security之类的CMD运行chrome,但没有帮助。

有什么想法我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

您可以做两件事

  1. 将文件放入应用程序的根目录,然后可以通过http://:// localhost:4200 / csv6677594787854925068.csv来访问文件,而不是file:/// C:/ Users / UserFolder / AppData / Local / Temp / csv6677594787854925025068 .csv

  1. 将响应头中的新文件设置为“ Access-Control-Allow-Origin:*”。