首页 > 解决方案 > 如何为具有 Excel 工作表文件的 InputStream 构建响应正文?

问题描述

我正在编写一个 get API 来获取存储在 src/main/resources 中的 excel 工作表文件。

InputStream 的内容为 excel 文件(xlsm 格式)。但响应是数据损坏。

@GetMapping("/downloadTemplate")
public ResponseEntity<?> downloadTemplate() throws IOException {
    String fn = "filename";

    try {
        File file = new File(getClass().getClassLoader().getResource(fn).getFile());
        InputStreamSource iss = new FileSystemResource(file);

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename= SimpleStandardTemplate.xlsm")
                .body(IOUtils.toByteArray(iss.getInputStream()));
    } catch (Exception e) {
        log.error("An error occurred while trying to downloadTemplate: {}", e);
        throw new ApiException(ApiErrorCode.DEFAULT_410, "Error while downloading");
    }
}

好像这条线有问题“body(IOUtils.toByteArray(iss.getInputStream()));” . 如果还有其他方法?否则可能是什么问题?

编辑:我认为问题在于内容长度。

标签: javaexcelspringrestspring-boot

解决方案


试试这个,用 spring-boot 测试1.5.6

@GetMapping("/export")
  public ResponseEntity<Resource> download() throws IOException {
    String fileName ="<file-path>";
    Resource resource = new FileSystemResource(fileName);
    return ResponseEntity.ok()
        .contentType(MediaType.parseMediaType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
        .body(resource);
  }

推荐阅读