Reputation: 871
My HTML file has the following command
<img src="/5/background" alt="" width="192" height="192">
Which I have bound to the following inside a @RestController in a Spring Boot application:
@RequestMapping(value = "/{connector}/background", method = RequestMethod.GET)
public File getConnectorBackgroundImage(@PathVariable("connector") int connector)
{
File image = new File("folder" + connector + "/myPicture");
return image;
}
I have done my debugging and I know the method is being entered, and I know the path is correct, but all that shows is the icon in the browser when there is a problem loading a picture.
What else am I missing?
Upvotes: 0
Views: 81
Reputation: 44745
Spring does not know how to handle the file that way. If you return a File
, the controller will simply show you the path to the file if you call the REST API.
The proper way to do it is to read the file as a byte[]
. Using commons-io you could come up with something like this:
File image = new File("folder" + connector + "/myPicture");
FileInputStream input = null;
try {
input = new FileInputStream(image);
return IOUtils.toByteArray(input);
} finally {
IOUtils.closeQuietly(input);
}
Another thing you shouldn't forget is to provide the mimetype. To do that you tweak the @RequestMapping
annotation a bit by providing the produces
property:
@RequestMapping(value = "/{connector}/background", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
This should do the trick.
EDIT: Didn't notice the comments, you already fixed it by yourself.
Upvotes: 1