|
| 1 | +package com.baeldung.spring.controller; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStream; |
| 5 | + |
| 6 | +import javax.servlet.ServletContext; |
| 7 | + |
| 8 | +import org.apache.commons.io.IOUtils; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.core.io.DefaultResourceLoader; |
| 11 | +import org.springframework.core.io.Resource; |
| 12 | +import org.springframework.core.io.ResourceLoader; |
| 13 | +import org.springframework.http.HttpHeaders; |
| 14 | +import org.springframework.http.HttpStatus; |
| 15 | +import org.springframework.http.MediaType; |
| 16 | +import org.springframework.http.ResponseEntity; |
| 17 | +import org.springframework.stereotype.Controller; |
| 18 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 19 | +import org.springframework.web.bind.annotation.RequestMethod; |
| 20 | +import org.springframework.web.bind.annotation.ResponseBody; |
| 21 | +import org.springframework.web.context.support.ServletContextResourceLoader; |
| 22 | + |
| 23 | +@Controller |
| 24 | +public class ImageController { |
| 25 | + |
| 26 | + @Autowired |
| 27 | + ServletContext servletContext; |
| 28 | + |
| 29 | + @RequestMapping(value = "/image-response-entity", method = RequestMethod.GET) |
| 30 | + public ResponseEntity<byte[]> getImageAsREsponseEntity() throws IOException { |
| 31 | + final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg"); |
| 32 | + byte[] media = IOUtils.toByteArray(in); |
| 33 | + |
| 34 | + final HttpHeaders headers = new HttpHeaders(); |
| 35 | + headers.setContentType(MediaType.IMAGE_JPEG); |
| 36 | + |
| 37 | + return new ResponseEntity<byte[]>(media, headers, HttpStatus.OK); |
| 38 | + } |
| 39 | + |
| 40 | + @RequestMapping(value = "/image-byte-array", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) |
| 41 | + public @ResponseBody byte[] getImageAsByteArray() throws IOException { |
| 42 | + final InputStream in = servletContext.getResourceAsStream("/WEB-INF/images/image-example.jpg"); |
| 43 | + return IOUtils.toByteArray(in); |
| 44 | + } |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | + @ResponseBody |
| 49 | + @RequestMapping(value = "/image-resource", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE) |
| 50 | + public Resource getImageAsResource() { |
| 51 | + ResourceLoader resourceLoader = new ServletContextResourceLoader(servletContext); |
| 52 | + return resourceLoader.getResource("/WEB-INF/images/image-example.jpg"); |
| 53 | + } |
| 54 | +} |
0 commit comments