如何从 AJAX 响应下载文件

How to download a file from an AJAX response

我正在向 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);
}

您可以直接下载 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>