上传javabean
/**
* Oracle 上传文件至BLOB字段
* @param myUpload 上传类对象
* @param path 上传路径
* @param serialNo 序列号
* @throws Exception
*/
public void InsertMsg(SmartUpload myUpload, String path, String serialNo)
throws Exception {
/* 设定不自动提交 */
Connection conn = getConnection();
Statement stmt = conn.createStatement();
PreparedStatement ps = null;
boolean defaultCommit = conn.getAutoCommit();
conn.setAutoCommit(false);
String strSQL = "";
try {
com.jspsmart.upload.File myFile = myUpload.getFiles().getFile(0);
if (!myFile.isMissing()) {
String FileName = myFile.getFileName();
String Filesize = myFile.getSize() + "";
/**
* 插入除blob外的其他信息
*/
strSQL =
"insert into T_CommFiles (serialNo,filename,filesize) values('"
+ serialNo
+ "','"
+ FileName
+ "','"
+ Filesize
+ "')";
ps = conn.prepareStatement(strSQL);
ps.executeUpdate();
ps.close();
ps = null;
String fileType = myFile.getContentType();
String ByteLen = String.valueOf(myFile.getSize());
java.io.File folder = new java.io.File(path);
if (!folder.exists() || folder.isFile())
folder.mkdirs();
myFile.saveAs(path + FileName);
java.io.File file = new java.io.File(path + FileName);
/**
* 清空BLOB字段
*/
String resetClob =
"UPDATE T_CommFiles SET files=EMPTY_BLOB() WHERE serialNo='"
+ serialNo
+ "'";
stmt.executeUpdate(resetClob);
strSQL =
"select files from T_CommFiles where serialNo='"
+ serialNo
+ "' for update";
ResultSet rs = stmt.executeQuery(strSQL);
/**
* 写入BLOB
*/
while (rs.next()) {
/* 取出此BLOB对象 */
oracle.sql.BLOB blob =
(oracle.sql.BLOB) rs.getBlob("files");
/* 向BLOB对象中写入数据 */
BufferedOutputStream out =
new BufferedOutputStream(blob.getBinaryOutputStream());
BufferedInputStream in =
new BufferedInputStream(new FileInputStream(file));
//blob.putBytes(1,b);
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
in.close();
out.close();
}
file.delete();
/* 正式提交 */
conn.commit();
rs.close();
stmt.close();
}
} catch (Exception ex) {
/* 出错回滚 */
System.out.println(ex.getMessage());
conn.rollback();
throw ex;
}
/* 恢复原提交状态 */
conn.setAutoCommit(defaultCommit);
conn.close();
}
download.jsp从BLOB读取文件
<%
String serialNo=request.getParameter("serialNo");
java.sql.Connection con = null;
DbConnection dbCon=new DbConnection();
try{
//连接数据库
con = dbCon.connectByIplanet();
//查询数据库
String str="select files from T_COMMFILES where serialNo='"+serialNo+"'";
PreparedStatement pst=con.prepareStatement(str);
ResultSet rs=pst.executeQuery();
while(rs.next())
{
//读取
oracle.sql.BLOB files = (oracle.sql.BLOB)rs.getBlob("files");
InputStream in = files.getBinaryStream();
response.setContentType("application/x-msdownload");
OutputStream os = response.getOutputStream();
byte[] b = new byte[1024];
int len;
while((len=in.read(b)) >0)
os.write(b,0,len);
//释放资源
os.close();
in.close();
}
rs.close();
con.close();
}catch(Exception e)
{
System.out.println(e);
}
%>