|
1 | 1 | package com.vianavitor.simplelibrarygame.controller.aux; |
2 | 2 |
|
| 3 | +import com.vianavitor.simplelibrarygame.exception.ResourceNotFoundException; |
3 | 4 | import jakarta.servlet.http.HttpServletRequest; |
4 | | -import org.springframework.core.io.InputStreamResource; |
| 5 | +import org.springframework.core.io.Resource; |
| 6 | +import org.springframework.core.io.UrlResource; |
5 | 7 | import org.springframework.http.MediaType; |
6 | 8 | import org.springframework.http.ResponseEntity; |
7 | 9 | import org.springframework.web.bind.annotation.*; |
8 | 10 |
|
9 | 11 | import java.io.InputStream; |
| 12 | +import java.net.MalformedURLException; |
| 13 | +import java.nio.file.Path; |
10 | 14 |
|
11 | 15 | @RestController |
12 | 16 | @RequestMapping("/api/image-render") |
13 | 17 | public class ImageRender { |
14 | 18 | @GetMapping(value = "/path") |
15 | | - @ResponseBody |
16 | | -// TODO: make it works to external images |
17 | | - public ResponseEntity<InputStreamResource> render(@RequestParam String path, HttpServletRequest req) { |
| 19 | + public ResponseEntity<Resource> render(@RequestParam String path, HttpServletRequest req) throws MalformedURLException { |
18 | 20 | String extension = path.split("[.]")[1]; |
19 | 21 | MediaType type = extension.equals("png") ? MediaType.IMAGE_PNG : MediaType.IMAGE_JPEG; |
20 | 22 |
|
21 | | - InputStream in = getClass().getResourceAsStream("/static/images/3.png"); |
| 23 | + Resource resource = new UrlResource(Path.of(path).toUri()); |
22 | 24 |
|
23 | | - if (in == null) { |
24 | | - throw new NullPointerException("InputStream (in) cannot be null"); |
| 25 | + if (!resource.exists() || !resource.isReadable()) { |
| 26 | + throw new ResourceNotFoundException("image is not readable or does not exists"); |
25 | 27 | } |
26 | 28 |
|
27 | 29 | return ResponseEntity.ok() |
28 | 30 | .contentType(type) |
29 | | - .body(new InputStreamResource(in)); |
| 31 | + .body(resource); |
30 | 32 | } |
31 | 33 | } |
0 commit comments