excel文件下载下来损坏 js_反应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.

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

解决方案

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

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值