Omar B.
Omar B.

Reputation: 501

display image from file system in jsp using spring boot

I have Java Web Application using Spring Boot, I want to display in JSP page ,images which are in an extern folder (E:/images) in file system. I looked too many pages in google,I found on stackoverflow a post that say I should write a servlet to get the image : am I missing something or should I do it with an other way , please give me more details I m kind of new to Spring. thanks for your help.

in my Controller :

@RequestMapping(value="/images",method = RequestMethod.GET)
    public @ResponseBody void affichimage(@RequestParam("id") Integer Iddd,HttpServletResponse response,HttpServletRequest request) throws IOException
    {
        Annonce annonce=new Annonce();
        annonce=annoncedao.findOne(Iddd);  // get the right annonce from 
         //database
         File imageFile = new File(annonce.getimage()); // in image I have 
            //the  link to images  ex : E:/images/image1.jpeg
        response.setContentType("image/jpeg");

        BufferedImage image = ImageIO.read(imageFile);
        ImageIO.write(image, "image/jpeg", response.getOutputStream());
    }

in JSP :

<  img class="imagesaffichage" src="/images?id=${annonce.id}" alt="No  image"/>

I also added this to my application :

public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
                .addResourceLocations("file:///E:/images/");
    }

Upvotes: 1

Views: 3372

Answers (1)

Omar B.
Omar B.

Reputation: 501

I found the solution , I had to change the above method :

@RequestMapping(value="/images",method = RequestMethod.GET)
   public @ResponseBody void affichimage(@RequestParam("id") Integer 
      Iddd,HttpServletResponse response,HttpServletRequest request) throws 
      IOException,NullPointerException
       {
        Annonce annonce=new Annonce();
        annonce=annoncedao.findOne(Iddd);  // get the right annonce from 
         //database          
        File imageFile = new File(img);
        response.setContentType("image/jpeg");
        InputStream in=new FileInputStream(imageFile);
        IOUtils.copy(in, response.getOutputStream());
       }

Upvotes: 1

Related Questions