oracle实例:BLOB操作


//上传文件

  public synchronized boolean insert_Wfiles(WebfilesBean wb) throws IOException, SQLException

  {

  boolean flag=false;

  //得到文件输入流

  String filePath = wb.getPath() + "\\" + wb.getFilename();

  File f = new File(filePath);

  InputStream fis = new FileInputStream(f);

  //定义输入流和输出流

  BufferedOutputStream out=null;

  BufferedInputStream in=null ;

  //插入一个空的Blob值

  String str1 = "insert into Webfiles(PATH,FILENAME,USERNAME,JOB_NO,ORDERFILE)values(?,?,?,?,EMPTY_BLOB())";

  ResultSet rs=null;

  PreparedStatement pst = null;

  try {

  // 这里一定要手工设置控制事务

  conn.setAutoCommit(false);

  pst = conn.prepareStatement(str1);

  pst.setString(1,ConvertString.converString1(filePath));

  pst.setString(2, ConvertString.converString1(wb.getFilename()));

  pst.setString(3, ConvertString.converString1(wb.getUsername()));

  pst.setString(4, wb.getJobno());

  pst.executeUpdate();

  String str2="select orderfile from Webfiles where Webfiles.job_no=? and Webfiles.filename=? for update";

  pst=conn.prepareStatement(str2);

  pst.setString(1, wb.getJobno());

  pst.setString(2, wb.getFilename());

  rs=pst.executeQuery();

  while (rs.next())

  {

  oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("orderfile");

  out = new BufferedOutputStream(blob.getBinaryOutputStream());

  in = new BufferedInputStream(fis);

  int c;

  //将实际文件中的内容以二进制的形式来输出到BLOB对象对应的输出流中

  while ((c=in.read())!=-1)

  {

  out.write(c);

  }

  in.close();

  out.close();

  }

  conn.commit();

  if (f.exists())

  f.delete();

  flag=true;

  return flag;

  } catch (SQLException e)

  {

  conn.rollback();

  e.printStackTrace();

  System.out.println("插入数据不成功");

  return false;

  } finally {

  pst.close();

  fis.close();

  }

  }

  //下载文件

  public void getdownFile1(String jobno,String filename,ServletOutputStream sos) throws Exception

  {

  ResultSet rs=null;

  PreparedStatement pst = null;

  BufferedInputStream in=null;

  try

  {

  //这里一定要手工设置控制事务

  conn.setAutoCommit(false);

  String str="SELECT orderfile from Webfiles wf where wf.job_no=? and wf.filename=?";

  pst = conn.prepareStatement(str);

  pst.setString(1, jobno);

  pst.setString(2, filename);

  rs=pst.executeQuery();

  while (rs.next())

  {

  oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("orderfile");

  in = new BufferedInputStream(blob.getBinaryStream());

  byte[] buf = new byte[1024];

  int hasRead=0;

  while((hasRead=in.read(buf))>0)

  {

  sos.write(buf, 0, hasRead);

  }

  in.close();

  sos.close();

  }

  conn.commit();

  conn.setAutoCommit(true);

  }

  catch(Exception e)

  {

  conn.rollback();

  e.printStackTrace();

  }

  finally

  {

  if (pst != null)

  {

  pst.close();

  }

  if (rs != null)

  {

  rs.close();

  }

  }

  }


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3