通过MyBatis实现图片数据的存储 与读取

开发环境:

Mybatis:3.0.5

MySQL:5.x

 

1. 数据库Scheme

--
-- Table structure for table `user_graphic_t`
--

DROP TABLE IF EXISTS `user_graphic_t`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user_graphic_t` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `graphic_data` blob,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=360 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

2. Mapper文件


		
		






		id,graphic_data

	

		INSERT INTO user_graphic_t (
		
		)
		values (
		#{id},,#{graphicData}
		)

	

3. 映射VO:

public class UserGraphicVo {

	private Long id;
	
	private byte[] graphicData;

       //get/set方法
}

4. DAO层调用

public void addUserGraphic(UserGraphicVo userGraphicVo) {
		getSqlSessionTemplate().insert("userGraphicVo.insertUserGraphic",  userGraphicVo);
}

5.  JSP页面展示图片

 6. Action处理

public void showReportImage() {
                response.setContentType("image/jpeg");

                if (!"".equals(id)) {
			List list = userGraphicService.findUserGraphicVoById(id);
			if(null != list && !list.isEmpty()){
				OutputStream os = null;
				try {
					os = response.getOutputStream();
					os.write(list.get(0).getGraphicData());
					os.flush();
				} catch (IOException e) {
					Log.info("读取文件出错!" + e.getMessage());
				} finally {
					if(null != os){
						try {
							os.close();
						} catch (IOException e) {
							Log.info("关闭文件输出流出错!" + e.getMessage());
						}
					}
				}				
			}
		}
	}

7. 参考资料

    http://springsfeng.iteye.com/blog/1630672

    http://blog.csdn.net/pzhtpf/article/details/7400606

    http://springsfeng.iteye.com/admin/blogs/1630698

    http://hi.baidu.com/dcjob/blog/item/cd0cb809d8e43e3ce824886a.html

你可能感兴趣的:(Spring/JPA/MVC)