guy19867 发表于 2013-2-7 19:16:18

SSH图片的上传和在页面的显示

首先,图片在hibernate的配置文件中要标示为:
<property name="photo"   type="org.springframework.orm.hibernate3.support.BlobByteArrayType">   <column name="PHOTO" />  </property> 这样图片在数据库中是以BLOB形式存储的。在对应的实体类中:
private byte[] photo; 将其定义为字符数组的形式。
上传:对应的form定义上传文件
public class StudentInfoForm extends ActionForm {       private FormFile         uploadFile ;      public FormFile getUploadFile() {return uploadFile;}    public void setUploadFile(FormFile uploadFile) {this.uploadFile = uploadFile;}   }  对应的jsp页面中声明:将实体类的photo属性作为隐藏域保存在页面中。
<tr><td width="10%" height="15" align="right" valign="middle" bgcolor="#F2F2F2">    照片 </td><td align="left" colspan="5" bgcolor="#FFFFFF">    <nested:hidden property="photo"></nested:hidden>    <html:file property="uploadFile"       onchange="selectFile'f1','uploadFile');" style="width: 223px;" /></td></tr> 以上当form提交时,执行相应的后台操作上传便完成了。
  下载:在具体的要下载图片的jsp页面中代码如下:
<td width="10%">照片 </td><td align="left" rowspan="8" ><nested:hidden property="photo" /><img src="StudentInfo.do? method=showWorkerPicture&id=${StudentInfoForm.saveObject.studentId}" /></td>     我利用的是在action中写一个没有 forward为空的方法来获取图片的信息。具体代码:
public ActionForward showWorkerPicture(ActionMapping mapping,ActionForm form, HttpServletRequest request,HttpServletResponse response) {ActionForward forward = null;Java代码               String studentId = request.getParameter("id");                   Long id = Long.parseLong(studentId.trim());                  CourseStudentBas condition = new CourseStudentBas();//条件对象             condition.setStudentId(id);               CourseStudentBas pageObject = null;//包含照片信息的队形。      try {         pageObject = this.getStudentInfoService().findById(condition);         byte[] imageBinary = pageObject.getPhoto();         response.setContentType("image/jpeg");          OutputStream outs = response.getOutputStream();         for (int i = 0; i < imageBinary.length; i++) {            outs.write(imageBinary);// 输出到页面         }         outs.flush();    } catch (Exception e) {   return forward;   } 
页: [1]
查看完整版本: SSH图片的上传和在页面的显示