【问题标题】:How to download excel file in spring boot using HttpHeaders?如何使用 HttpHeaders 在 Spring Boot 中下载 excel 文件?
【发布时间】:2020-07-07 17:32:51
【问题描述】:

我得到了一个结果文件,但在响应中我得到了乱码

这是我正在尝试的代码

    public ResponseEntity<InputStreamResource> getExcel(String filePath) throws Exception {
        try {
            Path excelPath = Paths.get(filePath);
            byte[] excel = Files.readAllBytes(excelPath);
            ByteArrayInputStream excelToByte = new ByteArrayInputStream(excel);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.add("Content-Disposition", "attachment; filename=ABCGeneratedExcel.xls");

            return ResponseEntity
                    .ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(new InputStreamResource(excelToByte));
            }
                catch (NoSuchFileException e) {
                System.out.prinln("does not exist");
            }

【问题讨论】:

  • 为什么要内联?使用附件
  • @Eklavya 我仍然遇到同样的问题。
  • 文件下载正确?然后在编辑器中打开

标签: java spring spring-boot http-headers


【解决方案1】:

您应该改用HttpServletResponse。并让 Spring 框架通过声明为 Controller 方法的参数来对其进行初始化。因为你会将excel文件写成二进制流,所以不要定义返回类型。 然后在设置excel下载的contentType和header后编写响应流。

public void getExcel(String filePath, HttpServletResponse response) {
    byte[] excel = Files.readAllBytes(excelPath);
    String fileName = "anyFileName.xlsx"
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    response.getWriter().write(excel);  // in fact, you need to surround this by try-catch block
}

【讨论】:

    【解决方案2】:
    Path filePath = pathToFolder.resolve(fileName).normalize();
    
            Resource resource = new UrlResource(filePath.toUri());
    
            if (resource.exists()) {
                return resource;
            } else {
                throw new NotFoundException(String.format("File %s not found", fileName));
            }
    

    文件的路径 - 在您的目录中,文件名 - 在您的目录中的文件名。

    下一步是:

    Resource resource = service.downloadFile(fileName);
    
        String contentType = null;
    
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException e) {
            log.info("Could not determine file type");
        }
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        }
        return ResponseEntity
                .ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, String.format(
                        "%s; filename=%s", content.name().toLowerCase(), resource.getFilename()
                        )
                )
                .body(resource);
    

    第一个 %s - 附件 - 用于下载,内联 - 用于在浏览器中呈现文件。 第二个 %s - 文件名(请注意,如果您将文件存储在文件系统中,请使用带扩展名的文件名)。

    【讨论】:

      猜你喜欢
      • 2019-12-03
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多