6

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?

Community
  • 1
  • 1
first_time_user
  • 417
  • 1
  • 5
  • 16
  • Open your browser's network console and check what the response contains. Post that here. – Sotirios Delimanolis Nov 03 '15 at 02:01
  • oh, looks like the type is still 'document'. But I set it in headers, so it should return image. Maybe I set it the wrong way? – first_time_user Nov 03 '15 at 02:06
  • What you currently have should properly set the content-type header. Check that your handler method is properly invoked. Note that `@ResponseBody` is unnecessary since your return type is `ResponseEntity`. Remove it. – Sotirios Delimanolis Nov 03 '15 at 02:08
  • hmm.. in the response header, content-type already image/jpeg, in response, it is not empty.. like "/9j/4AAQSkZJRgABAQE..." but I don't know why the browser doesn't not show it. I can check the byte array, so I think the method is invoked – first_time_user Nov 03 '15 at 02:31
  • Have you solved this issue? – Leos Literak Jun 28 '17 at 07:10

1 Answers1

1

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);
}
Bnrdo
  • 5,325
  • 3
  • 35
  • 63