使用Spring的jdbcTemplate读取数据库中BLOB字段并存储在本地并在页面显示

首先你已经搭建了Spring,我可以对数据库进行操作

code:

public    Map<String, Object> getUser(String id)   {
			String sql="select  * from  tUser   where  id="+id;
			Map<String, Object> map=jdbcTemplate.query(sql, new ResultSetExtractor() {

			@Override
			public Object extractData(ResultSet rs) throws SQLException,
					DataAccessException {
				// TODO Auto-generated method stub
				Map<String, Object> map=new HashMap<String, Object>();
				while (rs.next()) {  
					Blob blob=  rs.getBlob("TX");
					String xm=rs.getString("XM");
				        String qq=rs.getString("QQ");
                                        String dz=rs.getString("DZ");
					map.put("xm", xm);
					map.put("qq", qq);
					map.put("dz", dz); 
					InputStream ins = blob.getBinaryStream();
				        //定义文件的输出目录
				        File file=new File("D:/abc/""+xm+.png");  
				        OutputStream fout;
					try {
						fout = new FileOutputStream(file);
				                 //下面将BLOB数据写入文件
				                 byte[] b = new byte[1024];
				                 int len = 0;
				                 while ( (len = ins.read(b)) != -1) {
				                   fout.write(b, 0, len);
				                   }  
				      
				                  //依次关闭
						   fout.close();
						   ins.close();
					} catch ( Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
				return map;
			}
		});
		    
		   
			return   map;
			
		
		}

上面的代码从数据库读取了一个用户的信息,并将头像Blob字段的内容取出并保存在本地 。

接着讲保存在本地的图片显示在Jsp页面上 。

我使用的是springmvc,所以在controller上写如下代码:

@RequestMapping("/showtx")
	public void showtx(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
	    String xm=request.getParameter("xm");
	    FileInputStream inputStream ;
	    File f =new File("D:/abc/""+xm+.png"); 
          inputStream= new FileInputStream(f); 
          int i = inputStream.available();  
         //byte数组用于存放图片字节数据  
           byte[] buff = new byte[i];      inputStream.read(buff);      //记得关闭输入流     inputStream.close();      //设置发送到客户端的响应内容类型      response.setContentType("image/*");      OutputStream out = response.getOutputStream();      out.write(buff);      //关闭响应输出流      out.close();      }

在页面上写个图片框

<img src="<%=basePath %>showtx?xm=${user.xm}" height="150px" width="120px">
至此,访问页面之后,img会去请求showtx来获取图片。




猜你喜欢

转载自blog.csdn.net/xadjccl/article/details/79972864