This will show how to return a JPG image as Response body from a Spring MVC annotated controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@RequestMapping (value = "/get/{name}", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody public byte[] getImageByName(HttpServletRequest request, @PathVariable ("name") String name) { //curl -v http://localhost:8080/mydomain/image/get/xxx > /dev/null String realPath = request.getSession().getServletContext().getRealPath("/resources/images/static/thumbs/" + name); try { InputStream is = new FileInputStream(realPath); BufferedImage img = ImageIO.read(is); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(img, "jpg", bos); return bos.toByteArray(); } catch (FileNotFoundException e) { return null; //todo: return safe photo instead } catch (IOException e) { return null; //todo: return safe photo instead } } |
curl test:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
MacBook-2:catalog mirceastanciu$ curl -v http://localhost:8080/mydomain/image/get/test.jpg > /dev/null * About to connect() to localhost port 8080 (#0) * Trying ::1... % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0* connected * Connected to localhost (::1) port 8080 (#0) > GET /mydomain/image/get/test.jpg HTTP/1.1 > User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5 > Host: localhost:8080 > Accept: */* > < HTTP/1.1 200 OK < Server: Apache-Coyote/1.1 < Set-Cookie: JSESSIONID=121C65A4D3E55C9ADFB609ED46D8726F; Path=/mydomain/; HttpOnly < Content-Type: image/jpeg < Content-Length: 17934 < Date: Fri, 26 Oct 2012 22:10:43 GMT |