Sometimes pictures or files must be stored in the database due to certain needs (such as security). Of course, in general, especially when the files are relatively large, many people do not advocate storing files in binary form in the database. Now Oracle The access to files in the file is organized as follows (the idea is the same as the access in SQL Server2000. When storing, the binary byte stream of the image or file is stored in the data. When reading, the corresponding field in the database is read into the byte data, and then output ):
1. Create a database table in TOAD or SQLPlus.
1CREATE TABLE TEST_TABLE
2(
3 ID VARCHAR2(36 BYTE),
4 NAME VARCHAR2(50 BYTE),
5 PHOTO BLOB
6)
7
2. Create a new ASPX page, put a FileUpload control on the page, name it fileUp, and place two buttons named btnSave (save) and btnRead (read).
3. Execute the following code in the btnSave event to save pictures or files:
Save pictures (files) to Oracle
1StringBuilder sbSQL = new StringBuilder("insert into Test_Table(ID,Name,Photo) values(:ID,:Name,:Photo)");
2 OracleConnection cn = new OracleConnection(strCn);
3 OracleCommand cmd = cn.CreateCommand();
4 cmd.CommandText = sbSQL.ToString();
5 cmd.Parameters.Add(":ID", OracleType.VarChar, 36).Value = Guid.NewGuid().ToString();
6 cmd.Parameters.Add(":Name", OracleType.VarChar, 50).Value = fileUp.FileName; ;
7 int intLen = fileUp.PostedFile.ContentLength;
8 byte[] pic = new byte[intLen];
9 fileUp.PostedFile.InputStream.Read(pic, 0, intLen);
10 cmd.Parameters.Add(":Photo", OracleType.Blob).Value = pic;
11 try
12 {
13 cn.Open();
14 cmd.ExecuteNonQuery();
15}
16 catch (Exception ex)
17 {
18 Response.Write(ex.Message);
19}
20 finally
twenty one {
22 cn.Close();
twenty three }
24
4. The reading method is as follows:
Read pictures (files) from Oracle
1OracleConnection cn = new OracleConnection(strCn);
2OracleCommand cmd = cn.CreateCommand();
3cmd.CommandText = "select photo from test_table";
4try
5{
6 cn.Open();
7 MemoryStream stream = new MemoryStream();
8 IDataReader reader = cmd.ExecuteReader();
9 if (reader.Read())
10 {
11 byte[] pic = (byte[])reader[0];
12 //byte[] pic = (byte[])cmd.ExecuteScalar();
13 stream.Write(pic, 0, pic.Length);
14 //Bitmap bitMap = new Bitmap(stream);
15 //Response.ContentType = "image/Jpeg";
16 //bitMap.Save(Response.OutputStream, ImageFormat.Jpeg);
17 //The comment part can display the picture in IE instead of downloading the picture.
18 //The following method downloads the file directly
19 Response.ContentType = "application/octet-stream";
20 Response.AddHeader("Content-Disposition", "attachment;FileName= demo.JPG");
21 Response.BinaryWrite(pic);
22 Response.End();
twenty three }
twenty four
25}
26catch (Exception ex)
27{
28 Response.Write(ex.Message);
29}
30finally
31{
32 cn.Close();
33}
34
http://www.cnblogs.com/weiweictgu/archive/2006/11/17/563761.html