我正在使用Spring 4和Hibernate 4将图片上传到数据库并从中检索。 我已将multipart图像转换为字节数组并存储在数据库中。 我的问题是如何从数据库中检索该图像,并在JSP中显示字节数组,而不必将其存储在本地系统中。
我正在使用Spring 4和Hibernate 4将图片上传到数据库并从中检索。 我已将multipart图像转换为字节数组并存储在数据库中。 我的问题是如何从数据库中检索该图像,并在JSP中显示字节数组,而不必将其存储在本地系统中。
由于您没有提及存储图像的数据库结构,因此我假设您正在使用 blob
数据类型进行存储。
第一部分: ControllerClass
从数据库中检索图像后,您需要使用 Base64.encode
对该图像进行编码,并将其映射到您的 jsp(使用 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
第二部分: JSP
然后通过解码字节数组在JSP
上显示它。
<img id="myImg" name="myImg" src="data:image/jpg;base64,<c:out value='${myImage}'/>" >
我们实际上正在做的是
在DAO方法中
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;
}
@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;
}
你可以轻松地完成它。你需要设置一个控制器,当浏览器请求时,它将发送图像。但是在这里,控制器不会将其放入模型中以便提供给视图,而是直接生成HTTP响应。然后在你的JSP中,你只需指定相关的URL。
以下是可能的(部分)示例:
@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);
}