Search code examples
javaimagespring-mvcimage-conversionimageurl

Spring-MVC, Java : Creating URL for image saved on FileSystem


I am working on a Spring-MVC application in which for the user, we are saving the thumbnail on the filesystem itself. Now for chat, I want to create a URL for the thumbnail saved on the filesystem and pass it on in the frontend.

For example : Image is saved at

/home/username/datadir/personid.png

I would like to give the url something like :

domainname.com/personid.png

Please note PersonId is unique, so I can use that constraint. The part to save the image is complete, I just don't know how to create an image URL out of the file saved on File-System.

Any help would be nice. Thanks a lot.. :-)


Solution

  • You should intermediate this call with a request handler, something like

    @RequestMapping("/image/{personId}")
    @ResponseBody
    public HttpEntity<byte[]> getPhoto(@PathVariable String personId) {
        byte[] image = org.apache.commons.io.FileUtils.readFileToByteArray(new File([YOUR PATH] + File.separator + personId + ".png"));
    
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG); 
        headers.setContentLength(image.length);
        return new HttpEntity<byte[]>(image, headers);
    }
    

    Note also that you can use content analysis to determine the proper media type e.g. with the help of Apache Tika. This way you don't have to store filename, or hard-code the extension