有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

reactjs使用Java apache poi和React通过API发送xls

我正试图从JavaSpring服务器向react客户端发送一个xls文件

使用默认的ApachePOI构造函数创建xlsx文件,这并不好。为了覆盖它,我必须使用FileOutputStream创建文件

FileOutputStream outputStream = new FileOutputStream("file.xls");

但是我不能通过网络发送文件。我尝试使用以下答案:https://stackoverflow.com/a/54765335/10319765我引用:“下载文件时,您的代码需要逐块流式处理文件-这就是Java streams的用途。”

return ResponseEntity.ok().contentLength(inputStreamWrapper.getByteCount())
        .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
        .cacheControl(CacheControl.noCache())
        .header("Content-Disposition", "attachment; filename=" + "file.xls")
        .body(new InputStreamResource(inputStreamWrapper.getByteArrayInputStream()));

所以我的控制器正在发送InputStreamResource

如何使用我的FileOutputStream构造InputStreamResource

这是我的客户:

 axios.get('/issues/export', { responseType: 'arraybuffer' }).then(response => {
        if (response && !response.error) {
            const blob = new Blob([response.payload.data], {type: 'application/vnd.ms-excel'});
            saveAs(blob);
        }
    });

资料来源:https://stackoverflow.com/a/46331201/10319765

编辑:

我用一个技巧做到了这一点,在我写入FileOutputStream之后,我打开了一个FileInputStream并返回了值

    FileOutputStream outputStream = new FileOutputStream("file.xls");
    workbook.write(outputStream);
    workbook.close();
    final InputStream fileInputStream = new FileInputStream("file.xls");
    return fileInputStream;

但是现在,作为对客户端的响应返回的xls文件已损坏,其中包含奇怪的字符: enter image description here

enter image description here

excel文件应如下所示(在发送后取自myjava server): enter image description here


共 (1) 个答案

  1. # 1 楼答案

    问题解决了。最终,为了解决损坏的xls文件,我所做的是使用字节数组。控制器看起来完全相同,但现在返回类型为ResponseEntity<byte[]>。为了将InputStream转换为字节数组,我使用了IOUtils.toByteArray()方法

    客户端代码也发生了一些变化,因为现在类型不再是responseType: 'arraybuffer',而是'blob'

     axios.get('/issues/export', { responseType: 'blob' }).then(response => {
        if (response && !response.error) {
            const blob = new Blob([response.payload.data]);
            saveAs(blob);
        }
    });
    

    就这些