React excel download file is corrupt
I'm trying to load an Excel file in Reactjs by calling a Spring REST endpoint, but I'm having problems with a corrupted file.
Reaction to a 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 ok .. but looking at response.data looks like ...
"PKs J_rels/.rels j 0 }↵ {㴃1F ^Ơ 2 l%1I,c [
Tring to open the file I receive ... Could not open file due to unreadable data. Opening the file on the server is ok
Any ideas are appreciated
Greetings
+3
source to share
1 answer
You just need to add the response type to the axios request:
responseType: 'arraybuffer'
In my application, the following function loads the excel file:
function exportIssues() {
axios.get('/issues/export', { responseType: 'arraybuffer' })
.then((response) => {
var blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
fileSaver.saveAs(blob, 'fixi.xlsx');
});
}
+4
source to share