反应Excel文件下载损坏 [英] React excel file download corrupt

查看:470
本文介绍了反应Excel文件下载损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过调用Spring REST端点在Reactjs中下载Excel文件,但是我遇到了文件损坏的问题.

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.

回拨电话...

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

弹簧控制器....

@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文件,好吧...但是查看response.data看起来就像...

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

欢迎提出任何想法

欢呼

推荐答案

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

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

responseType: 'arraybuffer'

在我的应用程序中,以下函数下载excel文件:

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

这篇关于反应Excel文件下载损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆