最近工作中遇到从数据库中读取blob类型的图片,并在页面显示的问题,想了下,大概有两种方式,一是将数据转换成文件,保存在本地,然后将文件地址传到前台页面,读取保存的图片文件;二是将文件转换成数据流,直接在页面显示,我觉得第二个方法比较简单,而且处理速度更快点。下面我将我的操作过程记录下来,给大家一个参考。
思路、步骤:
1:从数据库读取blob图片
2:转换成数据流
3:显示在页面
首先,我们在springmvc中建立一个controller方法
@RequestMapping("/toolUtil/")
public class ToolUtil{
@AutoWired
private ToolUtilManager toolUtilManager;//持久层
/**
* 获取图片
* @param request
* @param response
*/
@RequestMapping("getPhoto_Blob")
public void getPhoto_Blob(HttpServletRequest request,HttpServletResponse response){
String id = request.getParameter("id");
//这个我就不详细写了,就是通过传递的id查询你要显示的图片
Map resultMap = toolUtilManager.getPhoto_Blob(id)
//blob就是你要显示的那张图片
Blob blob = (Blob) resultMap.get("Photo");
InputStream in = null;
try {
in = blob.getBinaryStream();
OutputStream out = response.getOutputStream();
data = new byte[(int)blob.length()];
int i = 0;
while((i=in.read(data))!=-1){
out.write(data);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
好了,这就是controller里的方法,这几行代码完成步骤1和步骤2,下面我们要在页面显示
/toolUtil/getPhoto_Blob.xhtml?id=1" width="128" height="185"/>
步骤3就完成了,现在你的图片就可以在页面显示了,简单方便。
代码手打,难免有漏字、错字、描述不清现象,欢迎大家批评指教,切勿人身攻击,如果觉得有用,就告诉我一声,给我点鼓励。