Reputation: 427
I need to return image in my Spring controller. I try answer in this Spring MVC: How to return image in @ResponseBody? but it's not working
my code is like this
@RequestMapping(value = "cabang/photo", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> getPhoto() throws IOException {
File imgPath = new File("D:\\test.jpg");
byte[] image = Files.readAllBytes(imgPath.toPath());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentLength(image.length);
return new ResponseEntity<>(image, headers, HttpStatus.OK);
}
but when I access it in browser, it doesn't show anything (just no picture icon). But if I read the image byte array, it is not empty. Do I miss anything in my code?
Upvotes: 6
Views: 8453
Reputation: 5474
Your code looks ok. Make sure you added ByteArrayHttpMessageConverter
to your application's list of http message converters.
Java Config :
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
ByteArrayHttpMessageConverter byteConverter = new ByteArrayHttpMessageConverter();
converters.add(byteConverter);
super.configureMessageConverters(converters);
}
Upvotes: 1