Save picture as XML and retrieve pic from xml file

<form id="form1" runat="server">   
    
<asp:FileUpload ID="FileUpload1" runat="server" />
    
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Button" />
</form>  
//Code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text;
public partial class Pages_PageTest : Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    
protected void Button1_Click(object sender, EventArgs e)
    {
        Stream F_Stream 
= this.FileUpload1.PostedFile.InputStream;
        BinaryReader br 
= new BinaryReader(F_Stream,System.Text.Encoding.Default);
        
byte[] data = new byte[F_Stream.Length];
        br.Read(data, 
0, data.Length);
        StringBuilder strb 
= new StringBuilder();
        strb.Append(Convert.ToBase64String(data));
        Pic pbj 
= new Pic();
        pbj.s_pid 
= strb.ToString();
        pbj.id 
= 3;
        FileStream fs 
= null;
        
try
        {
            XmlSerializer xs 
= new XmlSerializer(typeof(Pic));
            fs 
= new FileStream(Server.MapPath("~/a.xml"), FileMode.Create, FileAccess.Write);
            xs.Serialize(fs, pbj);

            fs.Close();
        }
        
catch (Exception ex)
        {
            
if (fs != null)
                fs.Close();
            
throw new Exception("Xml serialization failed!");
        }

        
        
    }
    
protected void Button2_Click(object sender, EventArgs e)
    {
        
        FileStream fs 
= null;
        
try
        {

            XmlSerializer xs 
= new XmlSerializer(typeof(Pic));
            fs 
= new FileStream(Server.MapPath("~/a.xml"), FileMode.Open, FileAccess.ReadWrite);
            Pic obj 
= xs.Deserialize(fs) as Pic;

          
            
byte[] data= Convert.FromBase64String(obj.s_pid);
            Response.BinaryWrite(data);
            Response.End();
            fs.Close();
        }
        
catch (Exception ex)
        {
            
if (fs != null)
                fs.Close();
            
throw new Exception("Xml serialization failed!");
        }
    }
}
public class Pic
{
    
public string s_pid;
    
public int id;
}

posted on 2009-09-22 18:06  博览潇湘  阅读(227)  评论(0编辑  收藏  举报

导航