Hi everyone, I am learning spring boot using Java ...
# server
m
Hi everyone, I am learning spring boot using Java not Kotlin (for now). I am stuck in serving static images. Currently, my app is serving one image with this code:
Copy code
@RequestMapping(value = "/my_image",
            method = RequestMethod.GET,
            produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity<byte[]> getMyImage() throws IOException {

        ClassPathResource imgFile = new ClassPathResource("static/images/user/my_image.png");

        byte[] bytes = StreamUtils.copyToByteArray(imgFile.getInputStream());

        return ResponseEntity
                .ok()
                .contentType(MediaType.IMAGE_PNG)
                .body(bytes);
    }
The thing is, I have 7 images, and I believe there has to be a better way than writing this method 7 times. Can someone point me in the right direction? I want generic method for serving images.
g
You can pass parameters to your controller function (which will be in your json payload at the request). With that you could pass the image name or an id for example
m
You mean like these :
@RequestMapping("/{imageName}"
etc etc and I search for a file, and then if it finds it, then it will return the image, if not I throw exception. Thanks pal, trying it now đŸ™‚
Thanks, it worked đŸ™‚
k
shouldnt you use something like this https://www.baeldung.com/spring-mvc-static-resources
g
Yes, I agree with @kqr, if your only goal is to serve static files you could do something like that đŸ˜ƒ
m
I see it is a standard way of serving static content… awesome đŸ™‚ thanks a lot