我有一个要下载xls文件的Web应用程序。 spring-boot中的控制器将通过get请求返回HttpServletResponse

@RequestMapping(method = RequestMethod.GET, value = "/export/{id}", produces = { "multipart/mixed", "multipart/form-data" })
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public void export(@PathVariable String id, HttpServletResponse response) {
    XSSFWorkbook wb = service.export(assessmentId);
    String filename="test.xlsx";
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment; filename=test.xlsx");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        wb.write(bos);
        byte[] barray = bos.toByteArray();
        InputStream is = new ByteArrayInputStream(barray);
        IOUtils.copy(is, response.getOutputStream());

    } catch (IOException e) {
        e.printStackTrace();
    }
}


在客户端中,我要将文件导出到xls,这是代码:

var blob = new Blob([data], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.style = "display: none";
a.href = objectUrl;
a.download = "test.xlsx";
document.body.appendChild(a);
a.click();


尝试打开xlsx文件时,文件损坏。

最佳答案

为什么不能仅仅send the file as a download from the controller?在HTML中使用类似

<a href="/export/124875"><i class="fa fa-download"></i></a>

09-05 21:33