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

标签 java rest api spring-boot image-processing

我正在为客户开发一个 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/

相关文章:

java - 在不同的文件类 java Android 中调用 EditText 值

javascript - 需要有关如何在 Express 中实际使用 Passport 身份验证策略的帮助

c# - 任务一直在等待激活

php - 自定义 WordPress 发布查询

java - Telosys 工具 Java - 从 MySQL 数据库生成 CRUD UI,BeanCreationException

java - 如何使用 servlet 下载文件 (.EXE)?

java - 如何在扫描仪中保存下一个字符串?

angularjs - 如何使用 Restangular 以简洁的方式执行特定的无父请求?

api - REST 风格的 API : How to handle translated textfields in representations?

api - Bokeh API 是否支持 3D 绘图?