微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用ssh向sqlserver2005数据库中保存image类型的二进制图片

1.首先设计数据库表,其中photo、photo2字段均为Image类型的。

2.建立实体bean对象,设置两个字段为byte[]如: private byte[] photo; private byte[] photo2;

3.建立hibernate与数据库的映射文件hbm.xml,其中photo、photo2字段的映射如下:

  <property generated="never" lazy="false" name="photo" type="binary">
   <column name="photo"/>
  </property>
   <property generated="never" lazy="false" name="photo2" type="binary">
   <column name="photo2"/>
  </property>

4.建立前台上传选择文件页面

    <form id="inputForm" action="./saveStudent.action" method="post" enctype="multipart/form-data">

             <tr>  
                <th class="tdtitle">上传图片:</th>
                <td class="tdcell"><input type="file" id="file" name="file" value="浏览"/></td>  
            </tr>
            <tr>  
                <th class="tdtitle">上传图片:</th>
                <td class="tdcell"><input type="file" id="file2" name="file2" value="浏览"/></td>  
            </tr>

  </form>

5.在后台action中创建File对象file,并写set、get方法。在save方法中作如下处理(将输入流转换为byte数组):

InputStream inputStream=null;
inputStream = new FileInputStream(file);
byte bytes[]=new byte[inputStream.available()];
inputStream.read(bytes);
inputStream.close();
inputStream=new FileInputStream(file2);
byte bytes2[]=new byte[inputStream.available()];
inputStream.read(bytes2);
inputStream.close();
price.setPhoto(bytes);
price.setPhoto2(bytes2);

显示函数中做如下处理:(从数据库中取得二进制数据,转换为输出流)

byte [] buf=null;
if(pro.equals("1")){
buf=list.get(0).getPhoto();
}else{
buf=list.get(0).getPhoto2();
}
response.setContentType("image/jpg");
OutputStream outputStream=response.getoutputStream();
outputStream.write(buf);
outputStream.flush();

显示前台页面作如下处理:

<tr><td>图片1:</td><td><img src="<%=basePath %>getimageStudent.action?no=<s:property value="student.no"/>&&kind=1"/></td></tr>  <tr><td>图片2:</td><td><img src="<%=basePath %>getimageStudent.action?no=<s:property value="student.no"/>&&kind=2"/></td></tr>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐