Skip to content

Commit 332332c

Browse files
refactor: make the RenderImage works with external folders
1 parent 7b7e915 commit 332332c

1 file changed

Lines changed: 10 additions & 8 deletions

File tree

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,33 @@
11
package com.vianavitor.simplelibrarygame.controller.aux;
22

3+
import com.vianavitor.simplelibrarygame.exception.ResourceNotFoundException;
34
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;
57
import org.springframework.http.MediaType;
68
import org.springframework.http.ResponseEntity;
79
import org.springframework.web.bind.annotation.*;
810

911
import java.io.InputStream;
12+
import java.net.MalformedURLException;
13+
import java.nio.file.Path;
1014

1115
@RestController
1216
@RequestMapping("/api/image-render")
1317
public class ImageRender {
1418
@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 {
1820
String extension = path.split("[.]")[1];
1921
MediaType type = extension.equals("png") ? MediaType.IMAGE_PNG : MediaType.IMAGE_JPEG;
2022

21-
InputStream in = getClass().getResourceAsStream("/static/images/3.png");
23+
Resource resource = new UrlResource(Path.of(path).toUri());
2224

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

2729
return ResponseEntity.ok()
2830
.contentType(type)
29-
.body(new InputStreamResource(in));
31+
.body(resource);
3032
}
3133
}

0 commit comments

Comments
 (0)