繁体   English   中英

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

[英]What is the ideal way to retrieve image path from database in spring-rest API?

我正在为客户开发一个Spring rest 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");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM