如何从AJAX响应下载文件
我向spring控制器发出一个AJAX POST请求,并返回一个字节数组作为响应。我想让它可以下载。最好的方法是什么 以下是我的实现:如何从AJAX响应下载文件,ajax,spring-boot,download,Ajax,Spring Boot,Download,我向spring控制器发出一个AJAX POST请求,并返回一个字节数组作为响应。我想让它可以下载。最好的方法是什么 以下是我的实现: var params = [[${params}]]; $("#download-button").click(function(e) { e.preventDefault(); $.ajax({ type: "POST", contentType: "application/json", url: "/patient-listing/e
var params = [[${params}]];
$("#download-button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
contentType: "application/json",
url: "/patient-listing/excel",
data: JSON.stringify(params),
success: function(result) {
var byteArray = result;
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(new Blob([byteArray], { type:'application/octet-stream' }));
a.download = "file.XLSX";
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
},
error: function(result) {
console.log('error');
}
});
});
在这里,即使下载了文件,也没有数据
控制器:
@PostMapping(value = "/patient-listing/excel", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getEmployeeReportXlsx(@RequestBody Param param) {
logger.info("Generating Excel report of param : " + param);
final byte[] data = poiService.getExcelFile(param);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
header.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=case-data-report.xlsx");
header.setContentLength(data.length);
return new ResponseEntity<>(data, header, HttpStatus.OK);
}
@PostMapping(value=“/patient listing/excel”,consumes=MediaType.APPLICATION\u JSON\u value)
公共响应性getEmployeeReportXlsx(@RequestBody Param Param){
logger.info(“生成参数的Excel报告:“+param”);
最终字节[]数据=PoiseService.getExcelFile(参数);
HttpHeaders header=新的HttpHeaders();
setContentType(MediaType.parseMediaType(“application/vnd.openxmlformats of cedocument.spreadsheetml.sheet”);
set(HttpHeaders.CONTENT_处置,“inline;filename=case data report.xlsx”);
header.setContentLength(data.length);
返回新的响应属性(数据、标题、HttpStatus.OK);
}
您只需下载excel,无需AJAX请求,
使用@GetMapping将POST方法更改为GET方法
@GetMapping(value = "/patient-listing/excel", consumes = MediaType.APPLICATION_JSON_VALUE)
在特里梅莱夫
<a class="sidebar-element" th:href="@{/patient-listing/excel}">
Generate Excel
</a>
您只需下载excel,无需AJAX请求, 使用@GetMapping将POST方法更改为GET方法
@GetMapping(value = "/patient-listing/excel", consumes = MediaType.APPLICATION_JSON_VALUE)
在特里梅莱夫
<a class="sidebar-element" th:href="@{/patient-listing/excel}">
Generate Excel
</a>