React excel文件下载损坏

时间:2017-04-17 21:47:50

标签: java excel spring reactjs apache-poi

我试图通过调用Spring REST端点来下载Reactjs中的Excel文件,但我遇到了损坏文件的问题。

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控制器......

@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();
    }

...服务

 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;
 }

当我执行上面的代码时,我得到一个excel文件o.k ...但是看看response.data看起来像......

"PKs��J_rels/.rels���j�0��}↵�{㴃1F�^Ơ�2��l%1I,c�[�

打开我收到的文件...由于数据不可读而无法打开文件。在服务器上打开文件是可以的

欢迎任何想法

干杯

1 个答案:

答案 0 :(得分:8)

您只需要为axios请求添加响应类型:

responseType: 'arraybuffer'

在我的应用程序下面的函数下载excel文件:

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');
    });
}