Spring Boot MVC Controller send image or binary data

In web server application, sending image data to client browser is quite common job. This can be easily achieved in Spring or Spring boot MVC Controller. Key things here is to specify proper Content-Type such as image/png or whatever and then return the raw binary data of the image.

Here is a sample code to demonstrate the same.

@Controller
public class ImageController {

    @RequestMapping("/images/{id}")
    public ResponseEntity<byte[]> getImage(@PathVariable("id") String id) throws IOException {
        String filename = "D:/images/" + id + ".png";
        InputStream inputImage = new FileInputStream(filename);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[512];
        int l = inputImage.read(buffer);
        while(l >= 0) {
            outputStream.write(buffer, 0, l);
            l = inputImage.read(buffer);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "image/png");
        return new ResponseEntity<byte[]>(outputStream.toByteArray(), headers, HttpStatus.OK);  
    }
}


References:


Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus