日期:2014-05-16  浏览次数:20427 次

使用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>