首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在spring-rest API中从数据库中检索图像路径的理想方式是什么?

在spring-rest API中从数据库中检索图像路径的理想方式是什么?
EN

Stack Overflow用户
提问于 2019-06-24 22:54:24
回答 1查看 2K关注 0票数 0

我正在为客户开发一个spring rest API。我能够保存在数据库中的字节格式的图像,也能够下载它。但是,android开发人员只需要图像的路径,这样他就可以使用该路径在应用程序上显示图像。

我不确定如何才能获得图像的路径,因为它是我保存在数据库中的数据,因为我没有将该文件保存在任何文件夹中。

有人能给我指路吗?解决这个问题的正确方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-24 23:09:19

为图像文件提供一个REST端点,提供MediaType图像的ResponseEntity,而不是JSON或您的传统格式。

代码语言:javascript
运行
复制
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

@RequestMapping(path = "/images/{imageId}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<Resource> getImage(@PathVariable Long imageId) {
    try {

        File file = imageService.getImage(imageId);

        Path path = Paths.get(file.getAbsolutePath());
        ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

        return ResponseEntity.ok().contentLength(file.length()).contentType(MediaType.IMAGE_JPEG).body(resource);
    } catch (Exception e) {
        throw new InternalServerException("Unable to generate image");
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56739204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档