I've got a simple controller which processes and serves an image.
@RequestMapping(method=RequestMethod.GET)
@ResponseBody
public byte[] GetProcessedImageResource(@RequestParam Long imageID) {
Image image = someDAO.getImageById(imageID)
someBusinessObject.processImage(image);
retu image == null ? null : image.getData();
}
@ModelAttribute
public void setSomeHeaders(HttpServletResponse response) {
response.setHeader("Content-Type", "image/png");
response.setHeader("isThisHowIAddHeaders", "yup");
}
This controller is used in two contexts:
-
Context one (which currently works perfectly - and which there is dozens of instances of all over the site): When I want to use a particular image on another page like:
<img id="imageHolder" src="getProcessedImageResource.ctl?imageID=12345"></img> -
context two(which I'm having issues with): The user just goes directly to a URL by visiting, say:
www.foo.bar.com/blah/getProcessedImageResource.ctl?imageID=12345in their browser(which naturally anyone can do once they've been shown the image)
When I intercept the response on the client side, I see "isThisHowIAddHeaders", "yup".... but I also see "Content-Type", "text/html;charset=ISO-8859-1"
In context one this works fine - the image is displayed without issue
In context two, spring-magic seems to try to marshall this bytestream into a full web page - it throws in the default header and footer and displays the image as text.
this causes two problems:
-
The image is displayed as gibberish encoding instead of an image:
.....QhÓÇÆ@BüN+?G*?3gÐèºÁ³?¯¨pTXX*ýAçýëßÒ8"¸òÿWÏ®M¦ K©æìÉ 8*oÍÚþýÀTPõæAj?.?äq*¢ê@ ?©¦Í¦÷'?¹7ì?ÞêNGçÓ~²? òò?^1?¥}Dê:Y¨¸?e¸úÛ?ûðaZã??W1¢?¡?
Aóë??ÓefSô ??[ÜbX1×ݵç ùõ¦*B?c]Güþ?p1¡{·Ò@?Áµ¡ãý·½?*+N?ø[´Ñ©ëÖÇÂÿ_~=yåü(À|¿ÔzÂê@ ¾?tÙ?ÉýpIÒÿãîêGcª?Dz?Á#?òÇ]þ.8æíÍÆ¢ºqkX}?¯¿yÐÿ«íé?á?Eÿ?® §õ_?'?ºqcίõCý?»8z~}_J..... -
This text is displayed - d- directly to users - and some of these images are user-submitted. I'll be honest XSS problems are my biggest conce here...
-
Retuing a ResponseEntity instead of using @ResponseBody
HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "image/png"); retu new ResponseEntity<byte[]>(image.getData(), headers, HttpStatus.FOUND);(and removing @ModelAttribute setSomeHeaders() )
-
Using 'setContentType' instead
headers.setContentType(MediaType.IMAGE_PNG); -
forcing spring to serve only the image data, with no header/footer/decoration of any kind - still get text/html content type, still get encoded image
-
Intercepting the response and manually changing the content-type back to 'image/[everything I can think of]' - just to see if that's the only problem - I get an actual image this time - but completely garbled(It's supposed to be a flower by the by...) :

Any ideas what I'm doing wrong here? The image seems to display fine when it's shown as part of an tag...but when the user references it directly, and the image is served in isolation, the browser seems to refuse to display it in any sensible maer.
