gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:59:57 25 4
gpt4 key购买 nike

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

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

任何人都可以给我指导吗?解决这个问题的正确方法应该是什么?

最佳答案

为图像文件提供 REST 端点,传递 MediaType Image 的 ResponseEntity,而不是 JSON/XML 或传统格式。

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");
}
}

关于java - 在 spring-rest API 中从数据库检索图像路径的理想方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56739204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com