Issue
I have a web application in which I want to download a xls file. The controller in spring-boot will return a HttpServletResponse
via a get request:
@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();
}
}
In the client I want to export the file to a xls and this is the code:
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();
I am getting file corrupt when trying to open the xlsx file.
Solution
Is there a reason why you can't just send the file as a download from the controller? In HTML use something like
<a href="/export/124875"><i class="fa fa-download"></i></a>
Answered By - DJDaveMark
Answer Checked By - Marilyn (JavaFixing Volunteer)