java - 字节[]到图像转换弹簧启动
问题描述
我需要在spring boot中使用byte []来进行图像转换,根据以下代码我可以获得图像,但是它无法显示。所以我需要在调用 API 时显示图像的解决方案,http://localhost:9000/files/d317447b-7235-47c5-9923-bc65aae89d76
@GetMapping("/files/{id}")
public ResponseEntity<byte[]> getFile(@PathVariable String id) {
FileDB fileDB = storageService.getFile(id);
log.info("{}->{}","FILES_GET_BY_ID:",id);
return ResponseEntity.ok()
.header(HttpHeaders.ACCEPT, "attachment; filename=\"" + fileDB.getName() + "\"")
.body(fileDB.getData());
}
最后我得到了解决方案。
@GetMapping("/files/{id}")
public ResponseEntity<byte[]> getFile(@PathVariable String id) {
FileDB fileDB = storageService.getFile(id);
log.info("{}->{}","FILES_GET_BY_ID:",id);
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_JPEG)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileDB.getName() + "\"")
.body(fileDB.getData());
}
解决方案
我认为您需要更改 HTTP 标头而不是使用 ACCEPT 使用标头 Content-Disposition 还将响应类型设置为相关类型。
推荐阅读
- spring-boot - Springboot 控制器无法加载 Thymeleaf html 页面
- php - 疯狂的 LDAP (AD) 密码更新问题 (php)
- android-studio - 我可以在房间数据库中自动增加 id,但是当刷新数据库时它显示双倍
- javascript - vue.js 应用程序中的未定义方法不返回数据
- azure - 使用 Azure Cli 删除 Azure 文件共享中的旧文件
- python - 熊猫每周时间表,包括假期
- node.js - 我需要在 NPM package.json 和主 index.html 中添加 Babel 和 React 还是只在一个地方就足够了?
- php - 使用 Str::random (或原生 php 方法)的两个标记重合的情况
- reactjs - 如何在 React Native 中实现类似 Android 片段的功能
- c# - 打开包含同名文件的 Zip 文件