转自:http://heisetoufa.iteye.com/blog/227243
http://hi.baidu.com/dugubao/item/8d02cd9dc5b3e2cbb6253104
http://www.360doc.com/content/09/1124/14/506716_9668190.shtml(重点参考)
http://school.cnd8.net/jsp/jiaocheng/32647.htm
http://blog.163.com/greencoat_man@126/blog/static/10261923520090147253890/
经参考上面的一些博客,结合自己的实践,发现可以通过两种方式实现图片保存到数据库当中。详见下面的代码
1.直接存储(经测试这种方式对于存储字段为long raw类型的也同样适用,下面的方法二就不行,图片也可以存储到long raw类型中)
public void StorePicture() throws ClassNotFoundException, SQLException, IOException{
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pwd);
PreparedStatement pstmt = conn.prepareStatement("insert into test_picture values(?,?)");
File file = new File("c:/测试.JPG");
InputStream is = new FileInputStream(file);
stmt = conn.createStatement();
pstmt.setString(1,"124");
//pstmt.setBinaryStream(2,is,(int)file.length());//这种写法和下面的写法都可以
pstmt.setBinaryStream(2,is,is.available());
pstmt.execute();
//pstmt.executeUpdate();//这种写法和上面的写法都可以
is.close();
pstmt.close();
conn.close();
}
2.先插入一个空的再存储。
public void StorePicture2() throws ClassNotFoundException, SQLException, IOException{
Class.forName(driver);
conn = DriverManager.getConnection(url, user, pwd);
//处理事务
conn.setAutoCommit(false);
Statement st = conn.createStatement();
//插入一个空对象
st.executeUpdate("insert into test_picture values(103,empty_blob())");
//用for update方式锁定数据行
ResultSet rs = st.executeQuery(
"select picture from test_picture where id=103 for update");
if (rs.next()) {
//得到java.sql.Blob对象,
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
//到数据库的输出流
OutputStream outStream = blob.getBinaryOutputStream();
File file = new File("c:/测试.JPG");
InputStream fin = new FileInputStream(file);
byte[] b = new byte[blob.getBufferSize()];
int len = 0;
while ( (len = fin.read(b)) != -1) {
outStream.write(b, 0, len);
//blob.putBytes(1,b);
}
fin.close();
outStream.flush();
outStream.close();
conn.commit();
conn.close();
}
}
在JSP实现文件Upload/Download可以分成这样几块:文件提交到形成InputSteam;InputSteam以BLOB格式入库;数据从库中读出为
InputSteam;InputStream输出到页面形成下载文件。先说BLOB吧。
1. BLOB入库
(1) 直接获得数据库连接的情况
这是Oracle提供的标准方式,
c6e管,理=L_
先插入一个空BLOB对象,然后Update这个空对象。代码如下:
//得到数据库连接(驱动包是weblogic的,没有下载任何新版本)
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:testdb", "test", "test");
//处理事务
con.setAutoCommit(false);
Statement st = con.createStatement();
//插入一个空对象
st.executeUpdate("insert into BLOBIMG values(103,empty_blob())");
//用for update方式锁定数据行
ResultSet rs = st.executeQuery(
"select contents from BLOBIMG where id=103 for update");
if (rs.next()) {
//得到java.sql.Blob对象,
软#qc的业:R网网
然后Cast为oracle.sql.BLOB
oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1).;
//到数据库的输出流
OutputStream outStream = blob.getBinaryOutputStream();
//这里用一个文件模拟输入流
File file = new File("d:\\proxy.txt");
InputStream fin = new FileInputStream(file);
//将输入流写到输出流
byte[] b = new byte[blob.getBufferSize()];
int len = 0;
while ( (len = fin.read(b)) != -1) {
outStream.write(b, 0, len);
//blob.putBytes(1,b);
}
//依次关闭(注意顺序)
fin.close();
outStream.flush();
outStream.close();
con.commit();
con.close();
(2) 通过JNDI获得数据库连接
在Weblogic中配置到Oracle的JDBC Connection Pool和DataSource,
GBTO垠gXNtHU~中$Yiv育G
绑定到Context中,假定绑定名为”orads”。
为了得到数据库连接,做一个连接工厂,主要代码如下:
Context context = new InitialContext();
ds = (DataSource) context.lookup("orads");
return ds.getConnection();
以下是BLOB写入数据库的代码:
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
Statement st = con.createStatement();
st.executeUpdate("insert into BLOBIMG values(103,empty_blob())");
ResultSet rs = st.executeQuery(
"select contents from BLOBIMG where id=103 for update");
if (rs.next()) {
//上面代码不变
//这里不能用oracle.sql.BLOB,管:$F&baIn国cT专TW]*t专I.管中d(w的(AgKqzLW*xH管Ut件G会报ClassCast 异常
weblogic.jdbc.vendor.oracle.OracleThinBlobblob = (weblogic.jdbc.vendor.oracle.OracleThinBlob) rs.getBlob(1);
//以后代码也不变
OutputStream outStream = blob.getBinaryOutputStream();
File file = new File("d:\\proxy.txt");
InputStream fin = new FileInputStream(file);
byte[] b = new byte[blob.getBufferSize()];
int len = 0;
while ( (len = fin.read(b)) != -1) {
outStream.write(b, 0, len);
}
fin.close();
outStream.flush();
outStream.close();
con.commit();
con.close();
2. BLOB出库
从数据库中读出BLOB数据没有上述由于连接池的不同带来的差异,只需要J2SE的标准类java.sql.Blob就可以取得输出流(注意区别
java.sql.Blob和oracle.sql.BLOB)。代码如下:
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
Statement st = con.createStatement();
//这里的SQL语句不再需要”for update”
ResultSet rs = st.executeQuery(
"select contents from BLOBIMG where id=103 ");
if (rs.next()) {
java.sql.Blob blob = rs.getBlob(1);
InputStream ins = blob.getBinaryStream();
//用文件模拟输出流
File file = new File("d:\\output.txt");
OutputStream fout = new FileOutputStream(file);
//下面将BLOB数据写入文件
byte[] b = new byte[1024];
int len = 0;
while ( (len = ins.read(b)) != -1) {
fout.write(b, 0, len);
}
//依次关闭
fout.close();
ins.close();
con.commit();
con.close();
3. 从JSP页面提交文件到数据库
(1)提交页面的代码如下:
<form action="handle.jsp" enctype="multipart/form-data" method="post" >
<input type="hidden" name="id" value="103"/>
<input type="file" name="fileToUpload">
<input type="submit" value="Upload">
</form>
(2)由于JSP没有提供文件上传的处理能力,只有使用第三方的开发包。网络上开源的包有很多,我们这里选择Apache Jakarta的
FileUpload,在http://jakarta.apache.org/commons/fileupload/index.html 可以得到下载包和完整的API文档。法奥为
adajspException
处理页面(handle.jsp)的代码如下
<%
boolean isMultipart = FileUpload.isMultipartContent(request);
if (isMultipart) {
// 建立一个新的Upload对象
DiskFileUpload upload = new DiskFileUpload();
// 设置上载文件的参数
//upload.setSizeThreshold(yourMaxMemorySize);
//upload.setSizeMax(yourMaxRequestSize);
String rootPath = getServletConfig().getServletContext().getRealPath("/") ;
upload.setRepositoryPath(rootPath+"\\uploads");
// 分析request中的传来的文件流,返回Item的集合,
// 轮询Items,如果不是表单域,就是一个文件对象。
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//如果是文件对象
if (!item.isFormField()) {
//如果是文本文件,可以直接显示
//out.println(item.getString());
//将上载的文件写到服务器的\WEB-INF\webstart\下,文件名为test.txt
//File uploadedFile = new File(rootPath+"\\uploads\\test.txt");
//item.write(uploadedFile);
//下面的代码是将文件入库(略):
//注意输入流的获取
…
InputStream uploadedStream = item.getInputStream();
…
}
//否则是普通表单
else{
out.println("FieldName: " + item.getFieldName()+"<br>");
out.println("Value: "+item.getString()+"<br>"); }
}
}
%>
4. 从数据库读取BLOB然后保存到客户端磁盘上
这段代码有点诡异,执行后将会弹出文件保存对话窗口,将BLOB数据读出保存到本地文件。全文列出如下:
<%@ page contentType="text/html; charset=GBK" import="java.io.*" import="java.sql.*"
import="test.global.ConnectionFactory"%><%
Connection con = ConnectionFactory.getConnection();
con.setAutoCommit(false);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(
"select contents from BLOBIMG where id=103 ");
if (rs.next()) {
Blob blob = rs.getBlob(1);
InputStream ins = blob.getBinaryStream();
response.setContentType("application/unknown");
//注释掉下面这句就不会弹出对话框了。
//response.addHeader("Content-Disposition", "attachment; filename="+"output.txt");
OutputStream outStream = response.getOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len=ins.read(bytes))!=-1) {
outStream.write(bytes,0,len);
}
ins.close();
outStream.close();
outStream = null;
con.commit();
con.close();
}
%>
第一步:建立数据库
create table test_img(id number(4),name varchar(20),img long raw);
第二步:(NewImg.html)
<html><head><title>添加图片</title></head>
<body>
添加图片<br>
<form method="post" action="insertNews.jsp">
图像ID:<input name="id" size="10">
<br>
选择图像:<input type="file" name="image">
<br>
<input type="submit" value="上传" name="submit" size="25">
<input type="reset" value="清除" name="clear" size="25">
<br>
</form>
</body></html>
第三步:插入数据库(InsertImg.jsp)
<%@ page language="java"%>
<%@ page contentType="text/html;charset=gb2312" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*"%>
<%@ page import="java.text.*"%>
<%@ page import="java.io.*"%>
<%
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); //com.microsoft.jdbc.sqlserver.SQLserveDriver
String url="jdbc:oracle:thin:@lubin:1521:b2bdb"; //jdbc:microsoft:sqlserver://127.0.0.1:1433; jdbc:microsoft.sqlserver://127.0.0.1:1433
Connection con=DriverManager.getConnection(url,"demo","demo");
//插入数据库
String sql="insert into test_img values (?,?,?)";
//获取传值ID
String id=request.getParameter("id");
//获取image的路径
String kk=request.getParameter("image");
//转换成file格式
File filename=new File(kk);
//将文件的长度读出,并转换成Long型
long l1=filename.length();
int l2=(int)l1;
//以流的格式赋值
FileInputStream fis=new FileInputStream(filename);
PreparedStatement ps =con.prepareStatement(sql);
ps.setString(1,id);
ps.setString(2,filename.getName());
ps.setBinaryStream(3,fis,l2);
//ps.setBinaryStream(3,fis,fis.available());
ps.executeUpdate();
//ps.execute();
ps.close();
fis.close();
out.println("ok!!!");
%>
第四步:显示图片(ShowImg.jsp)
<%@ page language="java" import="java.sql.*"%>
<%@ page import="java.io.*"%>
<%@ page contentType="text/html;charset=gb2312"%>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@lubin:1521:b2bdb";
String image_id = (String) request.getParameter("ID");
Connection con=DriverManager.getConnection(url,"demo","demo");
PreparedStatement sql=con.prepareStatement("select * from test_img WHERE id = " + image_id);
ResultSet rs = sql.executeQuery();
rs.next();
//输入img字段内容到in
InputStream in = rs.getBinaryStream("img");
//以下可是任何处理,比如向页面输出:
response.reset();
response.setContentType("image/jpeg");
byte[] b = new byte[1024];
int len;
while((len=in.read(b)) >0)
response.getOutputStream().write(b,0,len);
in.close();
rs.close();
%>