二进制流的存储、读取和显示(在浏览器)
存储:
数据库中(SQLServer)二进制流有一种专门的类型(image)表示,它是数据库定义的专门存放二进制流的类型。
在Java中,将文件首先转换成二进制流,File file = 得到文件的方法(返回的是File类型);然后FileInputStream f`is = new FileInputStream(file);fis就是最后要存放到数据库中的二进制流。注意,使用上述代码首先要import java.io.*;
因为File类和FileInputStream类都是IO包里面才有的。
接下来就要进行数据库的连接了。在Java中,连接数据库使用的是JDBC—ODBC桥,首先要在ODBC管理器中将数据源加载进来才行。具体步骤:
开始——设置——控制面板——管理工具——数据源(ODBC)。在UserDSN中选择添加,找到数据库并添加进来后就可以了。在Java代码中申明Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");然后Connection connection = DriverManager.getConnection("jdbc:odbc:数据库名字", "用户名", "密码");PreparedStatement statement = connection.prepareStatement(); statement. ExecuteQuery(INSERT INTO 表名 values(?,?));(?,?)代表有两个字段,具体应用的时候还要看你设计的表中的字段数。Statement.setBinaryStream(插入的位置标示,fis,文件的大小);
statement.executeUpdata();存储过程结束,当然,可以根据不同的类型将扩展名也一起存入到数据库中去。
取得扩展名,File file = 得到文件的方法(返回的是File类型);String filename = file.getName();int index = filename. LastIndexOf(“.”);String extendName = filename. Substring(index);这个时候extendName就是文件的扩展名,将extendName作为数据库的一个字段存入就可以了。

取出:
取出数据源并在浏览器中显示的时候就要借助于Servelet了,新建一个Servelet,然后在doGet(HttpServletRequest request, HttpServletResponse response)方法中指明连接的数据库和表和查询的语句及返回结果,与上面的情况很类似,           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connection=DriverManager.getConnection("jdbc:odbc:数据库名","用户名","密码");
定义用来存储照片数据的缓冲区buf ;byte [] buf=null;
定义一个查询语句

String searchSql="select * from 表名 where 查询条件"; 
 
 Statement stmt = connection.createStatement(); 
 
 ResultSet rs = stmt.executeQuery(searchSql); 
 
 将二进制流数据读入缓冲区 
 
   
   
   
   
   
  if (rs.next()) 
 
   
   
   
   
   
  { 
 
   
   
   
   
   
   
   
  buf = rs.getBytes(2); 
 
   
   
   
   
   
  } 
 
   
   
   
   
   
  else 
 
   
   
   
   
   
  { 
 
   
   
   
   
   
   
   
  buf = new byte[0]; 
 
   
   
   
   
   
  } 
 
   
   
   
  } 
 
   
   
   
  catch (Exception e) 
 
   
   
   
  { 
 
   
   
   
   
   
  Syst

em.out.println(e.toString());
}
到此,二进制流就被读入了这个buf缓冲区里面了。

显示:
这个时候还可以把文件的扩展名也取出来用来判断是什么类型的文件,然后告诉浏览器怎么样去解释。
如果是图象类型response.setContentType("image/*");
如果是其他的应用程序打开的response.setContentType("application/文件类型");

几个典型的文件类型: 
 
 ContentType(“image/*”);所有的图象类型 
 
 ContentType(“application/msword”);WORD文档 
 
 ContentType(“application/pdf”);PDF文档 
 
 ContentType(“text/xml”);XML数据 
 
 ContentType(“text/html; charset=gb2312);中文网页 
 


 然后建立一个文件的输出的输出流 
 
 OutputStream out = response.getOutputStream(); 
 

 将缓冲区的输入输出到页面 
 
   
   
   
  out.write(buf); 
 
 输入完毕,清除缓冲 
 
   
   
   
  out.flush(); 
 
 out.close(); 
 
 整个的结果就会在页面显示了,其实只要知道方法,整个的存储、读取过程是十分简单的。 
  

 

 

  /**读取sqlserver数据库中的image字段的方法。 
 
   
   
  * 
 
   
   
  */ 
 
   
  public void ReadImages() 
 
   
  { 
 
   
   
  ResultSet rs=null; 
 
   
   
   
  byte[] aa; 
 
   
   
   
  try { 
 
   
   
   
   
   
  aa = rs.getBytes("content"); 
 
   
   
   
   
   
  File file = new File("d://aa.jpg"); 
 
   
   
   
   
   
  FileOutputStream fout = null; 
 
   
   
   
   
   
  fout = new FileOutputStream(file); 
 
   
   
   
   
   
  fout.write(aa); 
 
   
   
   
   
   
  fout.close(); 
 
   
   
   
  } 
 
   
   
   
  catch (IOException ex) { 
 
   
   
   
   
   
  ex.printStackTrace(); 
 
   
   
   
  } 
 
   
   
   
  catch (SQLException ex) { 
 
   
   
   
   
   
  ex.printStackTrace(); 
 
   
   
   
  } 
 
   
  } 
 

   
  /** 
 
   
   
  * 向sql server数据库中的image字段中插入一副图片。 
 
   
   
  */ 
 
   
  public void insertImage() 
 
   
  { 
 
   
   
   
  long maxid=111; 
 
   
   
   
  java.sql.PreparedStatement ps=null; 
 
   
   
   
  // 
 
   
   
   
  String s = "bbbbbbbbbbbbbb"; 
 
   
   
   
  java.io.File file = new java.io.File("c://aa.jpg"); 
 

   
   
   
   
   
  try { 
 
   
   
   
   
   
   
   
  FileInputStream fin = new FileInputStream(file); 
 

   
   
   
   
   
   
   
  StringBufferInputStream in = new StringBufferInputStream(s); 
 
   
   
   
   
   
   
   
  //InputString in=java.sql.Blob.getBinaryStream(); 
 
   
   
   
   
   
   
   
  String sql = "insert  
  into forum(id,title,content,authorid,upid,datetime) values(?,?,?,?,?,?)"; 
 
   
   
   
   
   
   
   
  // ps = con.prepareStatement(sql); 
 
   
   
   
   
   
   
   
  ps.setLong(1, maxid); 
 
   
   
   
   
   
   
   
  ps.setString(2, "标题是什么"); 
 
   
   
   
   
   
   
   
  ps.setBinaryStream(3, fin, (int) file.length()); 
 
   
   
   
   
   
   
   
  //.................... 
 
   
   
   
   
   
   
   
  ps.executeUpdate(); 
 
   
   
   
   
   
  } 
 
   
   
   
   
   
  catch (SQLException ex) { 
 
   
   
   
   
   
   
   
  ex.printStackTrace(); 
 
   
   
   
   
   
  } 
 
   
   
   
   
   
  catch (FileNotFoundException ex) { 
 
   
   
   
   
   
   
   
  ex.printStackTrace(); 
 
   
   
   
   
   
  } 
 
   
   
   
  / 
 
   
  } 
  

 

 

  数据库字段类型为image 
 
 图片保存 
 
 <%@page contentType="text/html; charset=gb2312" language="java" 
 
 import="javax.sql.*" 
 
 import="javax.naming.*" 
 
 import = "java.sql.*" 
 
 import = "java.io.*" 
 
 %> 
 
 <jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" /> 
 
 <% 
 
 String add=null,medianame=null,exname=null,name1=null,sql=null,address=null,TypeMIME=null,SubTypeMIME=null,FilePathName=null,msg1=null; 
 
 String wwmj=null,wwmj1=null,EXT1=null; 
 
 int size1=0; 
 
 Connection Conn=null; 
 
 ResultSet Rs=null; 
 
 Statement Stmt = null; 
 
 add=request.getParameter("add"); 
 
 if (add==null) 
 
 { 
 
 add="0"; 
 
 } 
 
 if (add.equals("1")) 
 
 { 
 
 mySmartUpload.initialize(pageContext); 
 
 mySmartUpload.setTotalMaxFileSize(6000000); 
 
 //mySmartUpload.setAllowedFilesList("txt,doc,xls,jpg,gif"); 
 

 mySmartUpload.upload(); 
 
 for (int i=0;i<mySmartUpload.getFiles().getCount();i++) 
 
 { 
 
 com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i); 
 
 if (!myFile.isMissing()) 
 
 { 
 
 Context ctx = new InitialContext(); 
 
 DataSource ds = (DataSource)ctx.lookup("OracleDS"); 
 
 Conn = ds.getConnection(); 
 
 medianame=myFile.getFileName(); 
 
 exname=myFile.getFileExt(); 
 
 size1=myFile.getSize(); 
 
 TypeMIME=myFile.getTypeMIME(); 
 
 SubTypeMIME=myFile.getSubTypeMIME(); 
 
 FilePathName=myFile.getFilePathName(); 
 
 Statement aStmt = Conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE); 
 
 Rs = aStmt.executeQuery("SELECT MC,NR,DX,MIME,EXT FROM TEST"); 
 
 Rs.moveToInsertRow(); 
 
   
   
   
   
   
   
  Rs.updateString("MC",medianame); 
 
 Rs.updateInt("DX",size1); 
 
 Rs.updateString("MIME",TypeMIME); 
 
 Rs.updateString("EXT",exname); 
 
 byte buf[] = new byte[myFile.getSize()]; 
 
 for (int j=0;j<myFile.getSize();j++) 
 
 { 
 
 //out.println(myFile.getBinaryData(j)); 
 
 buf[j]=myFile.getBinaryData(j); 
 
 } 
 
 //File file1 = new File(FilePathName); 
 
   
   
   
   
   
  //FileInputStream fis = new FileInputStream(file1); 
 
   
   
   
   
   
  //InputStream is = fis; 
 
   
   
   
   
   
  //Rs.updateBinaryStream("NR",is,new Long(file1.length()).intValue()); 
 

 myFile.fileToField(Rs,"NR"); 
 
 //ByteArrayInputStream bas = new ByteArrayInputStream(buf); 
 

 //Rs.updateBytes("NR",buf); 
 
 Rs.insertRow(); 
 
   
   
   
   
   
   
  Rs.moveToCurrentRow(); 
 
 Rs.close(); 
 
 Conn.close(); 
 
 out.println("FieldName = " + medianame + "<BR>"); 
 
 out.println("Size = " + myFile.getSize() + "<BR>"); 
 
 out.println("FileExt = " + myFile.getFileExt() + "<BR>"); 
 
 out.println("FilePathName = " + myFile.getFilePathName() + "<BR>"); 
 
 out.println("ContentType = " + myFile.getContentType() + "<BR>"); 
 
 out.println("ContentDisp = " + myFile.getContentDisp() + "<BR>"); 
 
 out.println("TypeMIME = " + myFile.getTypeMIME() + "<BR>"); 
 
 out.println("SubTypeMIME = " + myFile.getSubTypeMIME() + "<BR>"); 
 
 break; 
 
 } 
 
 } 
 
 } 
 
 %> 
 
 <html> 
 
 <head> 
 
 <title>Untitled Document</title> 
 
 <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
 
 <link rel="stylesheet" href="../css/text.css" type="text/css"> 
 
 </head> 
 

 <body bgcolor="#FFFFFF" text="#000000"> 
 
 <form name="form1" method="post" action="save.jsp?add=1" enctype="multipart/form-data"> 
 
   
  <table width="100%" border="0" cellspacing="0" cellpadding="0"> 
 
   
   
   
  <tr> 
 
   
   
   
   
   
  <td colspan="2"> </td> 
 
   
   
   
  </tr> 
 
   
   
   
  <tr> 
 
   
   
   
   
   
  <td width="6%"><a href="aaaa.doc">asdasd</a> </td> 
 
   
   
   
   
   
  <td width="94%"> 
 
   
   
   
   
   
   
   
  <input type="file" style="width:50%" name="file"> 
 
   
   
   
   
   
   
   
  <input type="submit" name="Submit" value="上传"> 
 
   
   
   
   
   
  </td> 
 
   
   
   
  </tr> 
 
   
   
   
  <tr> 
 
   
   
   
   
   
  <td width="6%"> </td> 
 
   
   
   
   
   
  <td width="94%"> </td> 
 
   
   
   
  </tr> 
 
   
   
   
  <tr> 
 
   
   
   
   
   
  <td width="6%"> </td> 
 
   
   
   
   
   
  <td width="94%">文件大小应小于<font color="#FF0000">6</font>兆 </td> 
 
   
   
   
  </tr> 
 
   
  </table> 
 
 </form> 
 
 </body> 
 
 </html> 
 


回复: 
 数据提取 package Servlets; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import javax.sql.*; import javax.naming.*; public class getImage extends HttpServlet { private String CONTENT_TYPE = "image/gif"; public void init(ServletConfig config) throws ServletException { super.init(config); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int ID = 0; ServletOutputStream outt = response.getOutputStream(); try { ID = Integer.parseInt(request.getParameter("id")); //System.out.println(ID); }catch (Exception e){ response.sendRedirect("../ErroePage.jsp"); return; } try { byte[] buff = this.getCover(ID); response.setContentType(CONTENT_TYPE); outt.flush(); outt.write(buff); outt.flush(); }catch (IOException ioe){ ioe.printStackTrace(); } } private synchronized byte[] getCover(int ID1) { Context ctx=null; Connection Conn = null; Statement stmt = null; ResultSet rs = null; byte[] buf = null; try{ ctx = new InitialContext(); //DataSource ds = (DataSource)ctx.lookup("OracleDS"); DataSource ds = (DataSource)ctx.lookup("SqlServerDs"); Conn = ds.getConnection(); String searchSql="SELECT MIME,NR FROM TEST WHERE ID="+ ID1; stmt = Conn.createStatement(); rs = stmt.executeQuery(searchSql); rs.next() ; CONTENT_TYPE = rs.getString("MIME"); buf = rs.getBytes("NR"); //System.out.println(CONTENT_TYPE); }catch(Exception sqle){ System.err.println("Error in CoverServlet : getCover()-" + sqle); sqle.printStackTrace() ; }finally{ try { stmt.close() ; Conn.close() ; }catch (Exception e){ e.printStackTrace(); } } return buf; } public void destroy() { } } jsp页面 <html> <head> <title>Untitled Document</title> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> </head> <body bgcolor="#FFFFFF" text="#000000"> <p><a href="aaaa.doc">adfasdfasdf </a><img src="../servlet/getImage?id=1" width="103" height="34"> <a href="../servlet/getImage?id=2">SFADFASD</a> </p> <p> </p> <p>  </p> <form name="form1" method="post" action="../servlet/getImage?id=1"> <table width="95%" border="0"> <tr> <td> <input type="text" name="id" value="1"> <input type="submit" name="Submit" value="Submit"> </td> </tr> <tr> <td> </td> </tr> </table> </form> </body> </html> 你好好整