如何从AJAX响应下载文件



Im向spring控制器发出AJAX POST请求,并返回一个字节数组作为响应。我想把它下载下来。最好的方法是什么?

以下是我的实现:

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);
}

您可以在没有AJAX请求的情况下下载excel,使用@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>

最新更新