如何使用HttpHeaders在春季启动中下载Excel文件?

发布时间:2020-07-07 17:32

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

这是我正在尝试的代码

    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");
            }
回答1
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-文件名(请注意,如果要将文件存储在文件系统中,请使用带扩展名的文件名)。

回答2

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

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
}