java 将数据库中的blob字段转为图片显示在前端页面上

1.页面写法

  $("#zdytp").attr("src",ApiUrl+"/abc/getpic?orgid=8020");



2.后台写法(引入提示jar包即可)
IOUtils 引入依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

@RequestMapping(value = "/imageDisplay")
public void imageDisplay(String orgid, HttpServletResponse response, HttpServletRequest request) throws IOException, SQLException {
HashMap<String,Object> map = service.getById(orgid);//从数据库查询这条记录信息
if (map != null && map.size() > 0) {
byte[] bytes = (byte[]) map.get("orglogo");//orglogo为blob大字段 存储kb数据
response.setContentType("image/jpeg, image/jpg, image/png, image/gif"); //设置输出流内容格式为图片格式
InputStream in1 = new ByteArrayInputStream(bytes); //将字节流转换为输入流
IOUtils.copy(in1, response.getOutputStream());//将字节从 InputStream复制到OutputStream
}
String logoRealPathDir = request.getSession().getServletContext()
.getRealPath("/assets/images/icons.png");//获取默认图片路径
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
InputStream is = new FileInputStream(logoRealPathDir);

IOUtils.copy(is, response.getOutputStream());
}


另一种写法

@RequestMapping(value = "/showImage.do")
public void showImage(String id, HttpServletResponse response, HttpServletRequest request) throws IOException, SQLException {
User user=userService.getUserById(Integer.valueOf(id));
if(null != user){
//从数据库读取出二进制数据……
byte[] bb=user.getTp();
// 将图像输出到Servlet输出流中。
ServletOutputStream sos = response.getOutputStream();
sos.write(bb, 0, bb.length);
sos.close();
}
// 禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
}
 
posted @ 2020-07-17 10:38  颂先生  阅读(6171)  评论(0编辑  收藏  举报