Reputation: 2378
I am using spring 4 and hibernate 4 to upload and retrieve image to and from database. I have converted multipart image into byte array and stored in database. My query is how to retrieve that image from database and display the byte array in jsp without storing it in local system.
Upvotes: 6
Views: 7378
Reputation: 828
As you haven't mentioned your DB structure for storing the images, I assume that you are storing it in blob
datatype.
Part 1: ControllerClass
After retrieving the image from the DB, you have to encode that image using Base64.encode
and map that image to your jsp (using java.util.map
).
Map<String, Object> model = new HashMap<String, Object>();
model.put("myImage", Base64.encode(MyImage)); //MyImage (datatype 'byte[]') is the image retrieved from DB
return new ModelAndView("display", model); //display is the name of jsp on which you want to display image
Part 2: JSP
Then display it on the JSP
by decoding the byte array,
<img id="myImg" name="myImg" src="data:image/jpg;base64,<c:out value='${myImage}'/>" >
Upvotes: 4
Reputation: 148880
You can do it without problem. You have to set up a controller that will send the image when a browser requests it. But here, the controller does not put it in a Model to give it to a view, but directly generate the HTTP response. Then in your JSP, you simply indicates the relevant URL.
Here is a (partial) example of what it could be :
@RequestMapping(value = "/img/{imgid}")
public void getFile(HttpServletRequest request, @PathVariable(value = "imgid") long imgid, HttpServletResponse response) throws IOException {
contentType = "img/png"; //or what you need
response.setContentType(contentType);
// find the image bytes into into byte[] imgBytes
response.setContentLength((int) imgBytes.length);
response.setStatus(HttpServletResponse.SC_OK);
OutputStream os = response.getOutputStream();
os.write(imgBytes);
}
Upvotes: 0
Reputation: 3
Literally what we are doing is
in dao method
public InputStream get_user_photo_by_id(int id_user) throws Exception {
Blob blob_photo;
String sql = "Select b_photo_file from user_master where id_user = ?";
blob_photo = getJdbcTemplate().queryForObject(sql, new Object[] {id_user}, Blob.class);
if(blob_photo!=null)
return blob_photo.getBinaryStream();
else
return null;
}
In service method just returning inputstream to controller
In controller
@ResponseBody
@RequestMapping(value = "admin/user/{id}/photo", method = RequestMethod.GET, produces = MediaType.IMAGE_JPEG_VALUE)
public byte[] testphoto(@PathVariable("id") int id_sys_user, HttpSession ses) throws Exception {
byte[] thumb = null;
InputStream in = UserOps.getUserPhotobyId(id_sys_user);
if(in!=null){
thumb = IOUtils.toByteArray(in);
}
return thumb;
}
now just plug in admin/user/{id}/photo or any string you wish to use in < img src=""> as long as they match and you got your photo
Upvotes: 0