首页 > 解决方案 > 在 api 响应中返回名为“未定义”的文件,spring boot

问题描述

我面临一个奇怪的问题,我试图在 api 端点的响应中返回一个 excel 文件(.xlsx),并且返回的文件非常好,除了文件名总是以“undefined.xlsx”的形式出现。

api 在邮递员中工作正常(即文件名按预期出现)但是当通过浏览器(即我的应用程序)调用相同的 api 时,返回文件的文件名是'undefined.xlsx'。上述两种情况下的文件都很好,即所有数据、样式等都符合预期。

“Content-disposition”和“Content-Type”这两个标头在响应标头中也可见。

请让我知道我是否还有其他需要。

非常感谢。

我尝试了以下方法/方式来发送文件:

    1.
    @RequestMapping(value = "exportLogs/{deploymentId}")
    public ResponseEntity<byte[]> exportDeploymentLogs(@PathVariable String deploymentId) throws IOException {
        File workbook = myService.exportLogs(deploymentId);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition", String.format("attachment; filename=%s.xlsx",
                Utils.getFileName(workbook.getName())));
        httpHeaders.add("Content-Type", "application/vnd.ms-excel");
        return new ResponseEntity<>(org.apache.commons.io.FileUtils.readFileToByteArray(workbook), httpHeaders, HttpStatus.OK);
    }

2.

    @RequestMapping(value = "exportLogs/{deploymentId}")
    public ResponseEntity<byte[]> exportDeploymentLogs(@PathVariable String deploymentId) throws IOException {
        File workbook = myService.exportLogs(deploymentId);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition", String.format("attachment; filename=%s.xlsx",
                Utils.getFileName(workbook.getName())));
        httpHeaders.add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        return new ResponseEntity<>(org.apache.commons.io.FileUtils.readFileToByteArray(workbook), httpHeaders, HttpStatus.OK);
    }

3.

    @RequestMapping(value = "exportLogs/{deploymentId}")
    public Response exportDeploymentLogs(@PathVariable String deploymentId) throws IOException {
        File workbook = myService.exportLogs(deploymentId);
Response.ResponseBuilder responseBuilder = Response.ok(workbook);
        responseBuilder.header("Content-Disposition", String.format("attachment; filename=%s.xlsx",
                Utils.getFileName(workbook.getName())));
        responseBuilder.header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        return responseBuilder.build();
    }

4.

@POST
    @RequestMapping(value = "exportLogs2/{deploymentId}")
    public void exportDeploymentLogs2(@PathVariable String deploymentId,  HttpServletResponse response) throws IOException {
        File workbook = myService.exportLogs(deploymentId);
        response.setHeader("Content-disposition", "attachment; filename=" + Utils.getFileName(workbook.getName())+".xlsx");
        response.setContentType("application/vnd.ms-excel");
        IOUtils.copy(FileUtils.openInputStream(workbook), response.getOutputStream());
        response.flushBuffer();
    }

代码 -->

API端点:

    @RequestMapping(value = "exportLogs/{deploymentId}")
    public ResponseEntity<byte[]> exportDeploymentLogs(@PathVariable String deploymentId) throws IOException {
        File workbook = myService.exportLogs(deploymentId);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition", String.format("attachment; filename=%s.xlsx",
                Utils.getFileName(workbook.getName())));
        httpHeaders.add("Content-Type", "application/vnd.ms-excel");
        return new ResponseEntity<>(org.apache.commons.io.FileUtils.readFileToByteArray(workbook), httpHeaders, HttpStatus.OK);
    }

我的服务:

public File exportLogs(String deploymentId){
  DeploymentDetail dt = deployService.getDeploymentById(deploymentId);
  XSSFWorkbook workbook = excelService.createExcel(dt);//which will create and update some data in file.
  try {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                workbook.write(byteArrayOutputStream);
                return renameFile(byteArrayOutputStream.toByteArray(), fileName);
            }catch (Exception e){
                LOGGER.info("Error occurred while writing into stream {}", e);
                return File.createTempFile("Error", "xlsx");
            }
}
/*Although I can send the byte[] of workbook directly but thought that * there might be some problem in the workbook because of which the name * of the workbook is not showing, that's why I am creating a temp file 
* with the requestedName and sending this file back.
*/
private File renameFile(byte[] workbook, String fileName) throws IOException {
        File file = File.createTempFile(fileName, "xlsx");
        FileUtils.writeByteArrayToFile(file, workbook);
        return file;
    }

预期 - 具有预期文件名的有效文件。实际输出 - 名称为“undefined.xlsx”的有效文件。

标签: javaexcelspringrestspring-boot

解决方案


推荐阅读