数据库中保存图片等的字段类型设置为blob
界面,上传窗口
<div id="uploadWin" class="easyui-window" title="My Window" closed="true">
<br>
<strong>注意事项:</strong>
<br>
<div>1.请上传大小适合的图片<br>2.只能上传gif或者jpg类型的图片。</div>
<br>
上传文件:<input type="file" name="file" id="theFile"/>
<br/>
<input type="button" value="确认选择" onClick="return close_upload();"/>
<input type="button" value="取消" οnclick="return canclePhoto();"/>
<div id="upMessage" style="displan:hidden"></div>
</div>
</div>
action层
@Resource
private SystemService systemService;
private File file;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
systemService.saveCommanInfo(this.getFile());
service层
@Resource
private SystemDao systemDao;
public String saveCommanInfo(List<Object> list,File file) throws Exception {
return systemDao.saveCommanInfo(file);
}
dao层
Connection con = DB.getConnection();
PreparedStatement psta=con.prepareStatement("insert into zxtagl_tb_psrole_user_comman(sessions,username,name,photo,isconvener) values(?,?,?,?,?)");
System.out.println("上传的文件"+file);
if(null!=file) {
InputStream in=new BufferedInputStream(new FileInputStream(file));
psta.setInt(1, 1104);
psta.setString(2, "gzry");
psta.setString(3, "工作人员");
psta.setBinaryStream(4, in, (int)file.length());
psta.setString(5, "N" );
psta.execute();
in.close();
就这样很简单就可以把图片、word等以二进制的形式存到数据库了
下面说说如何读取
Blob blob=null;
while(rs.next()) {
blob=rs.getBlob(1);
........
}
if(null!=blob) {
//获取流对象后就好处理了
InputStream in=blob.getBinaryStream();
}