首页 > 解决方案 > 通过rest api spring boot和多个NULL下载文件

问题描述

我有一个从类路径rest controller下载一个CSV File

@GetMapping("/template/download")
    public ResponseEntity<byte[]> downloadCsv() throws IOException {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template.csv" );
        return ResponseEntity.status(HttpStatus.OK).headers(httpHeaders).body(csvUtil.downloadCsvTemplate());
    }

下面是我的downloadCsvTemplate()代码

public byte[] downloadCsvTemplate() throws IOException {
        File resource = new ClassPathResource("templates/template.csv").getFile();
        return util.convertFileToByteArray(resource);
    }
public byte[] convertFileToByteArray(File file) throws IOException {
        byte[] bytes = new byte[1024];

        try(FileInputStream fis = new FileInputStream(file);) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            for (int readNum; (readNum = fis.read(bytes)) != -1;) {
                bos.write(bytes, 0, readNum);
            }
        }

        return bytes;
    }

当我尝试点击 API 时,我可以下载包含内容的文件,但我得到了一些额外的内容,如下所示 -

在此处输入图像描述

关于如何仅获取以下内容的任何想法:

email,password,firstName
abc@abc.com,ABC@123,Test

感谢帮助。

标签: spring-bootcsv

解决方案


您在响应中看到原始数据的原因是 CSV 只不过是一个逗号分隔的字符串。尝试添加内容类型。

@GetMapping("/template/download")
public ResponseEntity<byte[]> downloadCsv() throws IOException {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set( HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=template.csv" );
    return ResponseEntity.status(HttpStatus.OK).contentType(MediaType.parseMediaType("text/csv")).headers(httpHeaders).body(csvUtil.downloadCsvTemplate());
}

推荐阅读