spring-boot - 通过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
感谢帮助。
解决方案
您在响应中看到原始数据的原因是 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());
}
推荐阅读
- javascript - 如何为自定义 lambda 授权器模拟 jsonwebtoken + jwsks-rsa
- wso2 - WSO2,将空的 SOAP 响应转换为空的 JSON
- angular - angular 9 web worker IE
- datatable - python-docx 表格样式不接受样式
- ios - 如何在快速加载 nib 文件时传递数据?
- javascript - 为什么我无法将类应用于靠近复选框的 span 元素?
- php - 当值大于 24 小时时,以分钟为单位计算停机时间从“0”开始
- python - 无论如何将特定的文本数据转换为 csv 格式并在 python 中给出标题名称?
- c++ - 如何在while循环中并行运行我的线程
- c++ - WIN32 项目 - 当我在我的解决方案中编译项目时,“LNK1104:无法打开mfc140d.lib”