Tapestry5 怎样将二进制的图片从数据库中显示出来,图片是以二进制数据的形式保存进数据库的,现在想以流的形式现在在tapestry5的页面上。求解,谢谢
解决方案 »
- websphere 调用webservice后session丢失
- JDK5的新特性有哪些????
- 在线求救----SSH类型转换之批量封装Set集合类型的属性的问题
- struts表单验证 关于失值的问题
- 我的工程,在TOMCAT下启动2次?这是怎么回事情啊???
- 求助:关于hibernate关联的问题?
- 求助:基于xfire的webservice?
- 新手求助!!struts 错误找不出来。请高手帮忙!HTTP Status 404 - Servlet action is not available
- resin 的读音是?
- ejb 中collection 问题。。。。
- java sql查询问题
- 求救!tomcat无法启动
----------------------------------------------------------------
1.从数据库中读取图片,关键也就是读取二进制字段的问题。下面是读取代码:
-------------------------------------------------------------------------------
public InputStream getBlob(String sql)
{
InputStream re = null;
DbInfo db = this.execute(sql);
ResultSet ra = db.getRs();
try {
if(ra.next())
{
re = ra.getBinaryStream(1); //关键是取值时用getBinaryStream,这样可以得到inputStream类型的对象。
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
db.close();
}
return re;
}
注:事实上我们也可以直接使用getObject(1)来得到不知道什么类型的对象,等到真正使用时再强制转换。
如:
public void setSd175_picture(Object sd175_picture) {
this.sd175_picture = (Blob)sd175_picture;
}
在方法参数用Object,在给属性附值时进行强制转换。
而Blob类型转换成InputStream类型就更简单了,如下:
------------------------------------------------------------------------
DownloadFile df = new DownloadFile();
Sql s = SqlFactory.getInstance();
String sql = "select sd175_picture from sd175 where sd175_style='02302-4EMIS'";
//InputStream in = s.getBlob(sql); //一般建议使用此方法,这样可以不浪费内存,因为后者会把一些不要用到的图片全部读出放在对象中。
List list = s.oQuery(Sd175.class, sql);
if(list!=null)
if(list.size()>0)
{
Sd175 obj = (Sd175)list.get(0);
Blob bl = obj.getSd175_picture();
try {
df.getFile(response,bl.getBinaryStream(),"good.jpg");
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
return null;
再看看getFile方法的实现:
------------------------------------------------------------------------------------------
/**
* 通过输入流,输出文件。
* @param response HttpServletResponse类型。
* @param in InputStream类型,文件输入流
* @param fileName 文件名
* @return 是否输出成功的状态,成功为:true,不成功为false;
*/
public boolean getFile(HttpServletResponse response,InputStream in,String fileName)
{
if(Ustring.getIsNull(fileName)) return false;
String ext = pf.getFileExt(fileName);
response.setContentType(ctype.getContentType(ext));
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
if(in==null)
return false;
ServletOutputStream output = null;
try {
int len=0;
if(in==null) return false;
output = response.getOutputStream();
if(output==null)
return false;
byte[] buffer = new byte[8192];
while(( len = in.read(buffer,0, 8192))!= -1)
{
output.write(buffer,0,len);
}
} catch (IOException e) {
return false;
}finally{
try {
if(in!=null)
in.close();
if(output!=null)
{
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}