如何在web中打开数据库中的文件

public String openFile() throws IOException, Exception
{

//获取数据库连接

//此方法只适用于jdbc的操作

SessionFactoryImplementor sessionFactory = (SessionFactoryImplementor) new Configuration().configure().buildSessionFactory();

ConnectionProvider cp = ((SessionFactoryImplementor)sessionFactory).getConnectionProvider();
Connection conn = cp.getConnection();
conn.setAutoCommit(false);
try {

byte[] Buffer = new byte[4096*5];

//查询数据库中第 id 条记录中的数据库文件

String sql = "select docsuffixalname,doccontent  from T_BAS_DOCUMENTYUAN where id="+id;
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet resultSet = pstmt.executeQuery();
if(resultSet.next()){
HttpServletResponse response =  ServletActionContext.getResponse();
response.reset();
String postfixName = resultSet.getString("Docsuffixalname");
// Blob blob = resultSet.getBlob("doccontent");
String postfix = "";
if(null != postfixName && !"".equals(postfixName)){
postfix = postfixName.substring(postfixName.lastIndexOf(".")+1);
if("doc".equals(postfix)){
response.setContentType("application/vnd.msword;charset=utf-8");
}else if("xls".equals(postfix)){
response.setContentType("application/vnd.ms-excel;charset=utf-8");
}else if("txt".equals(postfix)){
response.setContentType("text/plain;charset=utf-8");
}else if("pdf".equals(postfix)){
response.setContentType("application/pdf;charset=utf-8");
}
response.setHeader("Content-Disposition","attachment;filename=\""+ java.net.URLEncoder.encode(postfixName.replaceAll(" ", ""), "UTF-8")+ "\"");
OutputStream os = response.getOutputStream();
InputStream istream = resultSet.getBinaryStream("doccontent");
int size =0 ;
while((size = istream.read(Buffer)) != -1){
os.write(Buffer, 0, size);
}
os.flush();
os.close();
}
}
} catch (Exception e) {
}
return null;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值