Im trying to download an Excel file in Reactjs by calling a Spring REST endpoint but I'm running into issues with a corrupt file.
React call...
getFile(){
axios.get('get/download')
.then((response) => {
var blob = new Blob([response.data], {type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
filesaver.saveAs(blob, "excel.xlsx");
});
}
Spring controller....
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadExcelFile(final HttpServletResponse response) throws IOException {
response.setHeader("Content-Encoding", "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="file.xlsx");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
final File xls = service.createExcelFile(response);
final FileInputStream in = new FileInputStream(xls);
final OutputStream out = response.getOutputStream();
final byte[] buffer = new byte[8192];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
Service...
public File createExcelFile(final HttpServletResponse response) {
XSSFWorkbook xssfWorkbook = null;
final File xls = new File("excel.xlsx");
try {
final FileOutputStream fos = new FileOutputStream(xls);
xssfWorkbook = new XSSFWorkbook();
//setup excel file...
xssfWorkbook.write(fos);
xssfWorkbook.close();
}
catch (final Exception e) {
LOGGER.error(String.format("Something went wrong"));
}
return xls;
}
When I execute the above code I get an excel file o.k...but looking at response.data looks like...
"PKs??J_rels/.rels???j?0??}??{?1F?^??2??l%1I,c?[?
Tring to open the file I get...Could not open file due to unreadable data. Opening the file create on the server is ok
Any ideas welcome
Cheers
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…