我试图通过调用 Spring REST 端点在 Reactjs 中下载 Excel 文件,但我遇到了文件损坏的问题。
react调用...
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 看起来像......
"PKs��J_rels/.rels���j�0��}↵�{㴃1F�^Ơ�2��l%1I,c�[�
试图打开我得到的文件...由于无法读取的数据,无法打开文件。在服务器上打开文件创建就可以了
欢迎任何想法
干杯