如何从AJAX响应下载文件

时间:2020-04-08 12:41:31

标签: ajax spring-boot download

我向弹簧控制器发出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);
}

1 个答案:

答案 0 :(得分:0)

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