设为首页 收藏本站
查看: 1196|回复: 0

[经验分享] JAVA存取图片到ORACLE中的BLOB字段

[复制链接]

尚未签到

发表于 2016-8-7 06:50:57 | 显示全部楼层 |阅读模式
  转自:http://heisetoufa.iyunv.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();

       }
%>
 
 
JSP中如何上传图片到数据库中  
2009-01-14 19:25:38|  分类: sqlserver|字号 订阅


 
 
 
第一步:建立数据库 
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(); 
%>

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-254072-1-1.html 上篇帖子: Oracle自带的sql developer导入导出数据 下篇帖子: hibernate查询oracle数据库char类型字段
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表