Spring - display image on jsp file Spring - display image on jsp file spring spring

Spring - display image on jsp file


You cannot do it like this. Your image must be exposed somehow via normal URL. In Spring MVC create a controller that returns an image (raw data) under particular URL:

@RequestMapping(value = "/imageController/{imageId}")@ResponseBodypublic byte[] helloWorld(@PathVariable long imageId)  {  Image image = //obtain Image instance by id somehow from DAO/Hibernate  return image.getData();}

Now useit in your JSP page. This is how HTTP/HTML work:

<img src="/yourApp/imageController/42.png" alt="car_image"/>

In Spring MVC before 3.1 you might need to do a little bit more coding on controller side. But the principle is the same.


File file = new File("home/user/test.jpg");FileInputStream fis=new FileInputStream(file);ByteArrayOutputStream bos=new ByteArrayOutputStream();int b;byte[] buffer = new byte[1024];while((b=fis.read(buffer))!=-1){   bos.write(buffer,0,b);}byte[] fileBytes=bos.toByteArray();fis.close();bos.close();byte[] encoded=Base64.encodeBase64(fileBytes);String encodedString = new String(encoded);ModelMap map = new ModelMap();map.put("image", encodedString);

Now use it in your JSP page following as

<img src="data:image/jpeg;base64,${image}" alt="..." width="200" height="200">`


You may need to check this post. I have a similar problem like you and the solution is to convert the byte array to string and set in the img tag like below,

 <img src="data:image/jpg;base64,<c:out value='${bean.imageByteArrayString}'/>" />