UserEntityManager.java
@RequestMapping(value = "getImages.do", method = RequestMethod.GET)
public byte[] getImage(final String username) {
Blob img = null;
byte[] imgData = null;
sql = "SELECT UserPhoto FROM u_logininfo WHERE LoginName = ?";
try {
img = jdbcTemplate.queryForObject(sql, new Object[]{username}, new RowMapper<Blob>() {
@Override
public Blob mapRow(ResultSet rs, int arg1)
throws SQLException {
Blob blob = rs.getBlob("UserPhoto");
return blob;
}
});
imgData = img.getBytes(1, (int) img.length());
return imgData;
//File file = new File
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
这是我的控制器
UserController.java
@RequestMapping(value = "getImages.do" , method = RequestMethod.GET)
private ModelAndView viewImages(Model model){
String userName = (String)SecurityContextHolder.getContext().getAuthentication().getName();
byte[] image = userEntityManager.getImage(userName);
model.addAttribute("images", image);
return new ModelAndView("Fun Zone/Photo");
}
和jsp
<div class="col-sm-2" style="margin-top: 288px; margin-left: 291px;">
<img src="getImages.do">
</div>
我想使用Spring MVC 3在.jsp页面上显示图像但是图像不能在jsp中显示。
答案 0 :(得分:0)
我建议你改写控制器。似乎有很多事情并不完全符合它应有的方式。做这样的事情:
@RequestMapping(value = "getImages.do", method = RequestMethod.GET)
public void viewImages(HttpServletRequest request, HttpServletResponse response) throws IOException {
// get the image
String userName = (String)SecurityContextHolder.getContext().getAuthentication().getName();
byte[] image = userEntityManager.getImage(userName);
// get MIME type of the file
String mimeType = "application/octet-stream";
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) image.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=image.jpeg");
response.setHeader(headerKey, headerValue);
// get output stream of the response
OutputStream outStream = response.getOutputStream();
// get input stream and a fixed size buffer
InputStream is = new ByteArrayInputStream(image);
byte[] buffer = new byte[4096];
// write data into output stream
int read = -1;
while(read = in.read(buffer)) != -1) {
outStream.write(buffer, 0, read);
}
// close output stream
outStream.flush();
outStream.close();
}
并且还在UserEntityManager上删除了RequestMapping。