Java codepackage com.learn.util;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import com.learn.db.ConnectionFactory; // 自己实现一个连接工厂类
public class LoadImage {
/*
if exists (select * from sysobjects where id = object_id('ImageContainer') and
OBJECTPROPERTY(id, 'IsUserTable') = 1) drop table obj
CREATE TABLE [ImageContainer] (
[rid] [int] IDENTITY (1, 1) NOT NULL ,
[rname] [varchar] (100) COLLATE Chinese_PRC_CI_AS NULL ,
[rpath] [varchar] (500) COLLATE Chinese_PRC_CI_AS NULL ,
[rfilesize] [int] NULL ,
[rbinary] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
*/
public void getFileFromDatabaseByRid(int rid,
HttpServletResponse response) {
String strSQL = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rst = null;
ServletOutputStream sos = null;
BufferedInputStream bis = null;
try {
strSQL = "SELECT * FROM ImageContainer WHERE rid = ?";
conn = ConnectionFactory.getConnection(); // 取得Connection,代码略
pstmt = conn.prepareStatement(strSQL);
pstmt.setInt(1, rid);
rst = pstmt.executeQuery();
if (rst.next()) {
bis = new BufferedInputStream(rst.getBinaryStream("rbinary"));
sos = response.getOutputStream();
byte[] b = new byte[10 * 1024];
int len = 0;
while ((len = bis.read(b)) != -1) {
sos.write(b, 0, len);
}
bis.close();
sos.flush();
sos.close();
} else {
System.out.println("picture dose not exist!");
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally{
ConnectionFactory.close(rst);
ConnectionFactory.close(pstmt);
ConnectionFactory.close(conn);
}
}
}