Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return image in Spring REST to browser

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?

like image 262
first_time_user Avatar asked Nov 03 '15 01:11

first_time_user


Video Answer


1 Answers

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);
}
like image 111
Bnrdo Avatar answered Sep 28 '22 12:09

Bnrdo