Skip to content

Instantly share code, notes, and snippets.

@toffentoffen
Forked from kjunine/ImageController.java
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toffentoffen/39fa48a59087d9d88aac to your computer and use it in GitHub Desktop.
Save toffentoffen/39fa48a59087d9d88aac to your computer and use it in GitHub Desktop.
package image;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ImageController {
@Value("#{'resources/images/sample.jpg'}")
private Resource resource;
@RequestMapping(value = "/image1", method = RequestMethod.GET)
public void testImage1(HttpServletResponse response) throws IOException {
InputStream in = resource.getInputStream();
try {
response.setContentType("image/jpeg");
IOUtils.copy(in, response.getOutputStream());
} finally {
IOUtils.closeQuietly(in);
}
}
@RequestMapping(value = "/image2", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> testImage2() throws IOException {
InputStream in = resource.getInputStream();
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers,
HttpStatus.OK);
} finally {
IOUtils.closeQuietly(in);
}
}
@RequestMapping(value = "/image3", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public byte[] testImage3() throws IOException {
InputStream in = resource.getInputStream();
try {
return IOUtils.toByteArray(in);
} finally {
IOUtils.closeQuietly(in);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment