java - 如何为具有 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()));” . 如果还有其他方法?否则可能是什么问题?
编辑:我认为问题在于内容长度。
解决方案
试试这个,用 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);
}
推荐阅读
- ansible - Jinja2 遍历字典列表
- javascript - 谷歌自动电子邮件
- python - 安装 VSCode for python 后如何清除终端的命令提示符?
- c# - C# 提高 SIMD Sum 的性能
- php - ACF Pro 中继器 - 行索引和前导零的总计数
- c# - 使用随机 IV 在 C# 中加密/解密字符串时遇到问题
- javascript - 有什么方法可以将我的服务类注入 NodeJs 中的非服务注释类中?
- telegram-bot - 如何删除与节点 js 的电报聊天中的所有消息
- go - 具有相似路径的 Gorilla MUX 路由
- python - 将另一个类导入类python