Angular-SpringBoot下载了Excel文件HttpErrorResponse
问题内容:
我正在使用带有倾斜首页的Spring Boot服务器。我可以.xlsx
从前台下载文件。
这是我的代码:服务器端代码:
@GetMapping("/ExportExcel{date}")
public ResponseEntity<InputStreamResource> excelExportReport(@RequestParam Date date) throws IOException {
List<InterfaceTable> interfaceTables=interfaceTableRepo.afficheAHT(date);
ByteArrayInputStream in =ExportExcel.ahtToExcel(interfaceTables);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename=customers.xlsx");
return ResponseEntity
.ok()
.headers(headers)
.body(new InputStreamResource(in));
}
角服务:
ExportExcel(date:string){
return this.http.get<Operation[]>(this.exportUrl+date) }
问题是,HttpErrorResponse
即使它有一个角度,我也可以得到:
错误:SyntaxError错误:在XMLHttpRequest.onLoad(http:// localhost:4200 /
vendor.js:9948:51
)的JSON.parse()位置0处的JSON中的意外令牌P(位于ZoneDelegate.invokeTask(http://
localhost: 4200 /
polyfills.js:3240:31)在对象`
问题答案:
弹簧控制器
@GetMapping("/ExportExcel/{date}")
public void excelExportReport(@RequestParam Date date, HttpServletResponse httpServletResponse) throws IOException {
List<InterfaceTable> interfaceTables=interfaceTableRepo.afficheAHT(date);
ByteArrayInputStream in =ExportExcel.ahtToExcel(interfaceTables);
byte[] byteArray = new byte[in.available()];
try {
byteArrayInputStream.read(byteArray);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream out = new ByteArrayOutputStream(byteArray.length);
out.write(byteArray, 0, byteArray.length);
httpServletResponse.setContentType("text/csv");
httpServletResponse.addHeader("Content-Disposition", "attachment; filename=customers.csv");
OutputStream os;
try {
os = httpServletResponse.getOutputStream();
out.writeTo(os);
os.flush();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
前端服务
return this.http.get("/ExportExcel/", this.commonRepository.getRequestOptionsForCSV(URL.BEARER)).map(res => {
return {
filename: 'customers.csv',
data: res.blob()
};
});
前端组件
this.customerService.generateReportCsv(this.receiptReportPage.value).subscribe((results)=>{
console.log(results);
var url = window.URL.createObjectURL(results.data);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.setAttribute('target', 'blank');
a.href = url;
a.download = results.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
});