0

I wanted to get a background image in my html page where the image is coming from a rest api. Below is my html code

 <img class="background-img" id="container" ng-src="{{::backgroundImgUrl}}">

from my controller.js I'll be calling something like,

 var idx = Math.floor(Math.random() * (4 - 1)) + 1;
            $scope.backgroundImgUrl = "http://myrestsvc.mydomain.com/api/images/v3/" + idx;

My output should be like below,

<img class="background-img" id="container" ng-src="http://myrestsvc.mydomain.com/api/images/v3/5" src="http://myrestsvc.mydomain.com/api/images/v3/5">

This is the expected behavior and I'm not a java developer, how do I write a java rest api controller to achieve this?

I'm using Spring v1.3.3 and angularJS. Thanks in advance.

blue
  • 833
  • 2
  • 12
  • 39

1 Answers1

2

This answer may help

Aditional to provided answer: Add image_id to the @RequestMapping

And @PathVariable to your handler method parameters

@ResponseBody
@RequestMapping(value = "/api/images/v3/{id}", 
        method = RequestMethod.GET, 
        produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] handler(@PathVariable("id") int imageId){
    InputStream in = servletContext.getResourceAsStream("/image"+ imageId +".jpg");
    return IOUtils.toByteArray(in);
}
  • how do I return the image? as byte[]? or in the response ? could you please explain? – blue Dec 09 '16 at 17:46
  • Look at the [link provided](http://stackoverflow.com/a/16725508/4366471). To return response "as is" use annotation '@ResponseBody'. To return byte[] use IOUtils.toByteArray(). To hint browser that it's image add 'produces = MediaType.IMAGE_JPEG_VALUE' header to '@RequestMapping' annotation. – Wojciech Tomczyk Dec 12 '16 at 07:11