1

我需要将 ByteArrayInputStream 传递给 Web 层。在 ByteArrayInputStream 形成之后,我通过 RestController 到 serviceRest 再到 web 层。

我将对象导出到 .xlsx 并返回 ByteArrayInputStream

@Override
    public  ByteArrayInputStream exportProjectsToExcel(List<Projects> projectsList) {


        try {
            Workbook workbook = new XSSFWorkbook();

            Sheet sheet = workbook.createSheet("projects");

            Row row = sheet.createRow(0);

            CellStyle headerSellStyle = cellStyle(workbook, IndexedColors.SKY_BLUE);

            Cell cell = row.createCell(0);
            cell.setCellValue("projectId");
            cell.setCellStyle(headerSellStyle);

            cell = row.createCell(1);
            cell.setCellValue("description");
            cell.setCellStyle(headerSellStyle);

            cell = row.createCell(2);
            cell.setCellValue("dateAdded");
            cell.setCellStyle(headerSellStyle);

            for (int i = 0; i < projectsList.size(); i++) {

                Row dataRow = sheet.createRow(i + 1);
                CellStyle bodySellStyle = cellStyle(workbook, IndexedColors.WHITE);

                Cell bodyCell = dataRow.createCell(0);
                bodyCell.setCellValue(projectsList.get(i).getProjectId());
                bodyCell.setCellStyle(bodySellStyle);

                bodyCell = dataRow.createCell(1);
                bodyCell.setCellValue(projectsList.get(i).getDescription());
                bodyCell.setCellStyle(bodySellStyle);

                bodyCell = dataRow.createCell(2);
                bodyCell.setCellValue(projectsList.get(i).getDateAdded().toString());
                bodyCell.setCellStyle(bodySellStyle);
            }
            sheet.autoSizeColumn(0);
            sheet.autoSizeColumn(1);
            sheet.autoSizeColumn(2);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);

            return new ByteArrayInputStream(outputStream.toByteArray());

        } catch (IOException e) {
            e.printStackTrace();

            return null;
        }
    }

然后我需要通过 RestController 传递 ByteArrayInputStream

 @PostMapping(value = "/projectsDownload")
    public ByteArrayInputStream downloadExcelProjects( @RequestBody (required = false) List<Projects> projectsList) throws IOException {

        LOGGER.debug("**************************************************{}", projectsList);

        ByteArrayInputStream stream = excelFileExportService.exportProjectsToExcel(projectsList);

        return stream;
    }


使用 resttemplate 为 serviceRest

 @Override
    public ByteArrayInputStream exportProjectsToExcel(List<Projects> projectsList) {

        LOGGER.debug("////////////////////////////////////////////////exportProjectsToExcel({})", projectsList);

        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.ALL));
        HttpEntity<List> entity = new HttpEntity<>(projectsList, headers);
        ResponseEntity<ByteArrayInputStream> result = restTemplate.postForEntity(url + "/projectsDownload", entity, ByteArrayInputStream.class);
        return result.getBody();
    }

但我有以下例外

19:52:15 [http-nio-8088-exec-9] DEBUG c.e.b.c.r.c.DownloadExcelProjectsController - **************************************************[Projects(projectId=1, description=Create a web application based on SpringJDBC, dateAdded=2019-07-15, fileType=null, multipartFile=null, developers=null), Projects(projectId=2, description=Create a web application based on SpringBoot, dateAdded=2019-08-13, fileType=null, multipartFile=null, developers=null), Projects(projectId=3, description=Create a web application based on Hibernate, dateAdded=2020-01-17, fileType=null, multipartFile=null, developers=null)]
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Using @ExceptionHandler com.epam.brest.courses.rest_app.exception.CustomExceptionHandler#handleException(Exception, WebRequest)
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.m.m.a.HttpEntityMethodProcessor - No match for [*/*], supported: []
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.m.m.a.ExceptionHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class java.io.ByteArrayInputStream]
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.o.j.s.OpenEntityManagerInViewInterceptor - Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
19:52:16 [http-nio-8088-exec-9] DEBUG o.s.w.s.DispatcherServlet - Completed 500 INTERNAL_SERVER_ERROR

如果有任何帮助,我将不胜感激。谢谢。

4

1 回答 1

1

您可以将其转换为 Resource 对象 Spring 在编写对象时无法转换 Bytearrayinputstream,而其余模板也无法通过简单地传递 inputstream 来读取它。

试试这个代码:

Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);




File file = restTemplate.execute(FILE_URL, HttpMethod.GET, null, clientHttpResponse -> {
    File ret = File.createTempFile("download", "tmp");
    StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
    return ret;
});
 

于 2020-06-20T18:13:10.083 回答