React excel文件下载已损坏 [英] React excel file download corrupt

查看:47
本文介绍了React 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 文件 ok...但是查看 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');
    });
}

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

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