Java从数据库中读取Blob对象图片并显示的方法

图片存放读取是开发过程中经常使用的,有的图片是以路径方式存放在数据库中,有的是引用的插件以blob类型存放在数据库中,这里简单介绍以blob类型存放数据库如何读取? 仅供参考

1.适用环境

oracle数据库,springmvc,mabits

2. 核心Controller层

@RequestMapping(value = "imageDisplay")
	public void showImage(@RequestParam("employeeCode") String employeeCode,
			HttpServletResponse response, HttpServletRequest request)
			throws ServletException, IOException, SQLException {
			Map map = employeePhotoService.getById(employeeCode);//根据员工工号查询员工照片,如果不会写可继续往下看
			if (map != null && map.size() > 0) {
				BLOB blob = (BLOB) map.get("AVATAR");
				byte[] bytes = blob.getBytes(1L, (int) blob.length());  // blob.getBytes

				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("/img/default.jpg");//获取默认图片路径
		InputStream is = new FileInputStream(logoRealPathDir);

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

	}

3.页面展示层

只有一行代码,和img标签一样,直接引用方法传参,即可展示。 接下来是介绍第2步查询方法的写法,新手估计会出错

<img src="imageDisplay.htm?employeeCode=$employee.employeeCode" style="width:300px;height:350px;" class="img-thumbnail" alt="Responsive image"></a>

4.mapper层

public interface EmployeePhotoMapper {	
	public Map getById(@Param("employeeCode") String employeeCode);	
}

mabits配置


注意我划红线的,容易出错,接下来serverice就是直接引用mapper方法了,这里就不写了。ok,结束。

猜你喜欢

转载自blog.csdn.net/apbbbbb/article/details/79471262