我试图通过从angular2连接spring boot来下载excel文件。 我的启动如下所示
@RequestMapping(method = RequestMethod.GET,value="/downloadExcel/{weekEnd}",produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity downloadLastWeekOOOData(@PathVariable String weekEnd,HttpServletRequest request,HttpServletResponse response) throws IOException{
File result=new File("C:\\sayan\\poi-test.xls");
String type=result.toURL().openConnection().guessContentTypeFromName("poi-test.xls");
FileInputStream inputStream = new FileInputStream(new File("C:\\sayan\\poi-test.xls"));
byte[]out=org.apache.commons.io.IOUtils.toByteArray(inputStream);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("content-disposition", "attachment; filename=" + "poi-test.xlsx");
responseHeaders.add("Content-Type",type);
ResponseEntity respEntity = new ResponseEntity(out, responseHeaders,HttpStatus.OK);
System.out.println(respEntity.getBody());
return respEntity;
}
angular2代码看起来像:
downloadExcel(weekEnd: string) {
let downloadSuccess: boolean = false;
this.lastWeekOOOService.downloadExcel(weekEnd)
.subscribe(blob => {
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Report.xlsx";
link.click();
},
error => console.log("Error downloading the file."),
() => console.info("OK"));
}
服务看起来像:
downloadExcelOOO(weekEnd:string): Observable<Response> {
return this._http.get('http://localhost:8080/downloadExcel/'+weekEnd)
.map(res => new Blob([res],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
.catch(this.handleError);
}
但我收到的文件Report.xlsx已下载,已损坏。
答案 0 :(得分:-1)
将Excel复制为输入流,以在春季响应输出流。 在尖角后将httpoptions放在post中,在httpoptions中将参数responseType:'arraybuffer'放入'arraybuffer'。在订阅中直接使用blob中的arraybuffer对象