首页 > 解决方案 > 如何将 CoyoteInputStream 转换为 FileInputStream?

问题描述

我使用 fetch 从 js 文件 *.xls 的前端发送到后端:

const invokeImportPaymentsUpload = file => fetch("/rest/import", {
  method: "POST",
  credentials: "same-origin",
  body: file,
});

我在 java+spring 上有休息服务,所以我希望接收 FileInputStream 并解析文件,但使用 request.getInputStream() 接收 CoyoteInputStream。

    @RequestMapping(value = {"/import"}, method = RequestMethod.POST)
        public Map<String, List<Payment>> importPayments(HttpServletRequest request, HttpServletResponse response) throws IOException {
            ImportOutcome outcome = myService.import(request.getInputStream());
            ...

如何从 CoyoteInputStream -> FileInputStream 读取并解析?

通过像这样解析 FileInputSrtream,我在后端有一些遗留 byte[] bytes = IOUtils.toByteArray(fileInputStream); 但是它在其他地方使用,最好在我的情况下添加其他新解析?

标签: javaspringfetch

解决方案


它不能是 FileInputStream,因为数据不驻留在磁盘上的文件中。

如果您要求它在磁盘上,那么您必须将数据从磁盘复制CoyoteInputStream到磁盘,然后将 a 传递FileInputStream给需要它的代码。

但是,请注意,IOUtils.toByteArray()只需要一个InputStream,而不是一个FileInputStream。如果toByteArray()当前调用存在的代码被编写为 require ,FileInputStream那么它就是损坏的代码,需要修改才能使用InputStream,在这种情况下,您的问题就会消失。


推荐阅读