struts1整合hibernate保存图片到数据库并在页面显示

struts1整合hibernate保存图片到数据库

jsp

首先给要提交的表单添加下面属性

enctype="multipart/form-data"

添加input控件(这里我用的是html标签)

<html:file property="photoFile"/>

效果等同下面代码

<input type="file" name="photoFile">

form

添加下面属性,类型为FormFile

	private FormFile photoFile;
	public FormFile getPhotoFile() {
		return photoFile;
	}
	public void setPhotoFile(FormFile photoFile) {
		this.photoFile = photoFile;
	}

model

添加下面属性,类型为Blob

	private Blob photoFile;
	public Blob getPhotoFile() {
		return photoFile;
	}
	public void setPhotoFile(Blob photoFile) {
		this.photoFile = photoFile;
	}

hibernate映射文件

添加对应属性,类型为java.sql.Blob

<property 
			name="photoFile"
			type="java.sql.Blob"
			column="photoFile"
			insert="true"
			length="200"
			update="true"
			not-null="false"/>

action

action进行数据处理

			//拿到图片
			FormFile file = personForm.getPhotoFile();
			//图片转换成二进制
			byte[] byteOfFile = file.getFileData();
			//二进制转换成Blob
			Blob blob = (Blob) Hibernate.createBlob(byteOfFile);
			person.setPhotoFile(blob);

personForm为jsp传过来的表单
person为你的model对象
hibernate保存person即可进行保存

显示在jsp页面上

jsp代码:调用action里面的getImg(…)方法

 <img src="/bysj/personForm.do?method=getImg">

action代码:用下面方法遍历所有得到的数据(我这里只拿了一个数据)即可,记得return null

try {
			for (Person person : personList) {
				Blob photo = person.getPhotoFile();
				InputStream in = photo.getBinaryStream();
				OutputStream out = response.getOutputStream();
				byte[] buf = new byte[1024];
				int len;
				while ((len = in.read(buf)) != -1) {
					out.write(buf, 0, len);
				}
				in.close();
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值