图片在xml和数据库的存储和在web页的显示

一种是用字节数组表示二进制数据

<% @ Page Language = " C# "   %>
<% @ Import Namespace = " System.Xml "   %>
<% @ Import Namespace = " System.IO "   %>
<% @ Import Namespace = " System.Xml.XPath "   %>

< script runat = " server " >
    
void  Page_Load( object  sender, EventArgs e)
    
{        
        
        
string xmlFilePath = @"C:\Employees.xml";
        
string imageFileName = @"C:\Employee.jpg";
        
try
        
{
            
using (XmlWriter writer = XmlWriter.Create(xmlFilePath))
            
{
                
//Start writing the XML document
                writer.WriteStartDocument(false);
                writer.WriteStartElement(
"employee");
                writer.WriteAttributeString(
"id""1");
                writer.WriteStartElement(
"image");
                writer.WriteAttributeString(
"fileName", imageFileName);
                
//Get the size of the file
                FileInfo fi = new FileInfo(imageFileName);
                
int size = (int)fi.Length;
                
//Read the JPEG file
                byte[] imgBytes = new byte[size];
                FileStream stream 
= new FileStream(imageFileName, FileMode.Open);
                BinaryReader reader 
= new BinaryReader(stream);
                imgBytes 
= reader.ReadBytes(size);
                reader.Close();
                
//Write the JPEG data
                writer.WriteBinHex(imgBytes, 0, size);
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
                
//flush the object and write the XML data to the file
                writer.Flush();
                lblResult.Text 
= "File is written successfully";
            }
  
        }
       
        
catch (Exception ex)
        
{
            lblResult.Text 
= "An Exception occurred: " + ex.Message;
        }
        
    }


</ script >

< html xmlns = " http://www.w3.org/1999/xhtml "   >
< head runat = " server " >
    
< title > Writing Images  using  XmlWriter </ title >
</ head >
< body >
    
< form id = " form1 "  runat = " server " >
    
< div >
        
< asp:label id = " lblResult "  runat = " server "   />
    
</ div >
    
</ form >
</ body >
</ html >

读取显示
System.Xml.XPath.XPathDocument xdoc  =   new  XPathDocument(xmlFilePath);
            XPathNavigator xNav 
=  xdoc.CreateNavigator();  
            XPathNodeIterator nodes 
=  xNav.Select( " employee/image " );
            
string  file  =   string .Empty;
            
while (nodes.MoveNext())
            
{
                file 
= nodes.Current.Value;
            }

            
int  size  =  System.Text.Encoding.Default.GetByteCount(file);
            
            XmlReader xmlRead 
=  XmlReader.Create(xmlFilePath);
            
while (xmlRead.Read())
            
{
                
if(xmlRead.NodeType == XmlNodeType.Element && xmlRead.Name == "image")
                
{
                    
                    
byte[] bb = new byte[size];
                    xmlRead.ReadElementContentAsBinHex(bb, 
0, size);
                    Response.BinaryWrite(bb);
                }

            }


第二种是 FileUpload上传图片
<% @ Page Language = " C# "   %>

<% @ Import Namespace = " System.Data.SqlClient "   %>

< script runat = " server " >
  
string  CanUploadExt  =   " |.jpg|.gif|.bmp|.png|.jpeg| " ;
  
protected   void  Page_Load( object  sender, EventArgs e)
  
{
    
if (!Page.IsPostBack)
    
{
      
string ConnectionString = "Data Source=.;Initial Catalog=pubs;User Id=sa;Password=;";
      SqlConnection cn 
= new SqlConnection(ConnectionString);
      
string sql = "select id,Title from UserList Order By id DESC";
      cn.Open();
      SqlCommand cmd 
= new SqlCommand(sql, cn);
      GridView1.DataSource 
= cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
      GridView1.DataBind();
      cn.Close();
      cn.Dispose();
    }

  }


  
protected   void  Button1_Click( object  sender, EventArgs e)
  
{
    
if (FileUpload1.HasFile)
    
{
      
string FileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
      
if (FileExt.Length < 1)
      
{
        
return;
      }

      FileExt 
= FileExt.ToLower();
      
if (CanUploadExt.IndexOf("|" + FileExt + "|"== -1)
      
{
        
return;
      }

      
string ContentType = FileUpload1.PostedFile.ContentType;
      
byte[] fileData = FileUpload1.FileBytes;
      
string sql;
      sql 
= "INSERT INTO UserList (Title,ContentType,Photo) Values(@Title,@ContentType,@Photo)";
      
string ConnectionString = "Data Source=.;Initial Catalog=pubs;User Id=sa;Password=;";
      SqlConnection cn 
= new SqlConnection(ConnectionString);
      cn.Open();
      SqlCommand cmd 
= new SqlCommand(sql, cn);
      cmd.Parameters.Add(
"@Title", System.Data.SqlDbType.NVarChar);
      cmd.Parameters.Add(
"@ContentType", System.Data.SqlDbType.VarChar);
      cmd.Parameters.Add(
"@Photo", System.Data.SqlDbType.Image);
      cmd.Parameters[
"@Title"].Value = TextBox1.Text;
      cmd.Parameters[
"@ContentType"].Value = ContentType;
      cmd.Parameters[
"@Photo"].Value = fileData;
      cmd.ExecuteNonQuery();
      cn.Close();
      cn.Dispose();
    }

    Response.Redirect(Request.UrlReferrer.ToString());
  }

</ script >

< html xmlns = " http://www.w3.org/1999/xhtml " >
< head runat = " server " >
  
< title > FileUpload 服务器控件 </ title >

  
< script type = " text/javascript "  language = " javascript " >
  var CanUploadExt 
=   " <%=CanUploadExt %> "
  function CheckExt()
  
{
    var oFile 
= document.getElementById('<%=FileUpload1.ClientID %>')
    var ext 
= oFile.value.substr(oFile.value.lastIndexOf("."))
    
if(ext.length < 1)
    
{
      alert(
"请选择图像文件。")
      
return false
    }

    
else
    
{
      ext 
= ext.toLowerCase();
      
if(CanUploadExt.indexOf("|" + ext + "|"== -1)
      
{
        alert(
"请选择图像文件:" + CanUploadExt)
        
return false
      }

    }

    
return true
  }

  
</ script >

</ head >
< body >
  
< form id = " form1 "  runat = " server " >
    
< asp:GridView ID = " GridView1 "  runat = " server "  AutoGenerateColumns = " false " >
      
< Columns >
        
< asp:BoundField HeaderText = " 姓名 "  NullDisplayText = " 未输入 "  DataField = " Title "   />
        
< asp:ImageField HeaderText = " 照片 "  DataImageUrlField = " id "
         DataImageUrlFormatString
= " ShowImageCS.aspx?id={0} "  NullImageUrl = " ~/images/none.gif " >
        
</ asp:ImageField >
      
</ Columns >
    
</ asp:GridView >
    姓名:
< asp:TextBox ID = " TextBox1 "  runat = " server " ></ asp:TextBox >
    
< asp:FileUpload ID = " FileUpload1 "  runat = " server "   />
    
< asp:Button ID = " Button1 "  runat = " server "  OnClick = " Button1_Click "  OnClientClick = " return CheckExt() "
      Text
= " 上传 "   />
  
</ form >
</ body >
</ html >

显示
<% @ Page Language = " C# "   %>
<% @ Import Namespace = " System.Data.SqlClient "   %>
< script runat = " server " >
  
protected   void  Page_Load( object  sender, EventArgs e)
  
{
    Response.Clear();
    
int IsOkID;
    
bool strImageID = Int32.TryParse(Request.QueryString["id"], out IsOkID);
    
if (!strImageID)
    
{
      Response.ContentType 
= "image/gif";
      Response.WriteFile(
"~/images/none.gif");
      
return;
    }

    
string ConnectionString = "Data Source=.;Initial Catalog=pubs;User Id=sa;Password=;";
    SqlConnection cn 
= new SqlConnection(ConnectionString);
    
string sql = "select ContentType,Photo from UserList Where id=@id";
    cn.Open();
    SqlCommand cmd 
= new SqlCommand(sql, cn);
    cmd.Parameters.Add(
"@id", System.Data.SqlDbType.Int, 4);
    cmd.Parameters[
"@id"].Value = IsOkID;
    SqlDataReader myDataReader;
    myDataReader 
= cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
    
if (myDataReader.Read())
    
{
      Response.ContentType 
= myDataReader["ContentType"].ToString();
      Response.BinaryWrite((
byte[])myDataReader["Photo"]);
    }

    
else
    
{
      Response.ContentType 
= "image/gif";
      Response.WriteFile(
"~/images/none.gif");
    }

    cn.Close();
    cn.Dispose();
    Response.End();
  }

</ script >

你可能感兴趣的:(xml)