使用Struts1实现文件上传(二)
在使用Struts1实现文件上传(一)中,我将文件保存在服务器端的硬盘里,有没有办法将其保存在Oracle10g数据库中呢?答案是肯定的,只需要对程序稍加改造就可以实现将文件保存在数据库中。用到时再将文件从数据库中还原出来供用户下载。
一、新建Oracle10g数据表
- create
table UploadFiles - (
-
fileId number not null, -
fileName varchar2(100) not null, -
fileContent long raw not null, -
filePubDate date not null - )
二、将上传文件保存在数据库
- UploadForm
uploadForm = (UploadForm) form; - FormFile
uploadFile = uploadForm.getUploadFile(); -
- Connection
conn = null; - PreparedStatement
ps = null; -
- try
{ -
-
Class.forName("oracle.jdbc.driver.OracleDriver"); -
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:DataBaseName","username","password"); -
String sql = "insert into pic (fileName,fileContent,filePubDate) values (?,?,?)"; -
ps = conn.prepareStatement(sql); -
ps.setString(1, uploadFile.getFileName()); -
ps.setBinaryStream(2, uploadFile.getInputStream(), uploadFile.getFileSize()); -
ps.setDate(3, new Date()); -
ps.executeUpdate(); -
- }
catch (Exception e) { -
e.printStackTrace(); - }
三、将文件从数据库中还原出来
- Connection
conn = null; - PreparedStatement
ps = null; - ResultSet
rs = null; -
- <strong>InputStream
input = null;</strong> -
- try
{ -
-
Class.forName("oracle.jdbc.driver.OracleDriver"); -
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:DataBaseName","username","password"); -
String sql = "select * from UpLoadFiles where id = 3"; -
ps = conn.prepareStatement(sql); -
rs = ps.executeQuery(); -
if(rs.next()){ -
<strong>input = rs.getBinaryStream("pic");</strong> -
} -
-
//根据需要操作InputStream对象的代码; -
-
- }
catch (Exception e) { -
e.printStackTrace(); - }
finally { -
try { -
rs.close(); -
ps.close(); -
conn.close(); -
} catch (Exception e) { -
e.printStackTrace(); -
} - }