Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React excel file download corrupt

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

like image 445
rogger2016 Avatar asked Apr 17 '17 21:04

rogger2016


1 Answers

You just have to add response type to the axios request:

responseType: 'arraybuffer'

In my application following function downloads 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');
    });
}
like image 176
Ajinkya Avatar answered Sep 29 '22 10:09

Ajinkya