我正在为客户开发一个spring rest API。我能够保存在数据库中的字节格式的图像,也能够下载它。但是,android开发人员只需要图像的路径,这样他就可以使用该路径在应用程序上显示图像。
我不确定如何才能获得图像的路径,因为它是我保存在数据库中的数据,因为我没有将该文件保存在任何文件夹中。
有人能给我指路吗?解决这个问题的正确方法是什么?
发布于 2019-06-24 15:09:19
为图像文件提供一个REST端点,提供MediaType图像的ResponseEntity,而不是JSON或您的传统格式。
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");
}
}
https://stackoverflow.com/questions/56739204
复制