一、操作要點:
將文件轉換爲二進制,再將二進制轉回爲文件
將文件寫入到XML,再讀出來顯示或者還原
將文件寫入到數據庫,再讀取出來顯示或者還原
二、學習知識點:
二進制操作的類:FileStream(文件流)、BinaryReader(二進制流讀取器)、BinaryWriter(二進制流寫入器)
三、操作步驟:
(1)新建類:fileToData.cs
using System.IO;
/// <summary>
/// fileToData 的摘要說明
/// </summary>
public class fileToData
{
public fileToData() //構造函數
{ }
/// <summary>
/// 將傳進來的文件轉換成字符串(二進制)
/// </summary>
/// <param name=" FilePath">待處理的文件路徑</param>
/// <returns>String</returns>
public static string FileToBinary(string FilePath)
{
FileStream fs=new FileStream(FilePath,FileMode.Open,FileAccess.Read);
//利用新傳來的路徑實例化一個FileStream對象
int filelength = Convert.ToInt32(fs.Length);
//得到對象的大小
Byte[] filebyteArray=new byte[filelength];
//申明一個byte數組
BinaryReader br = new BinaryReader(fs);
//申明一個讀取二進制流的BinaryReader對象
for (int i = 0; i < filelength; i++)
{ //循環數組大小那麼多次
br.Read(filebyteArray, 0, filelength); //第一個數組用0表示
//將數據讀取出來放在數組中
}
string strData = Convert.ToBase64String(filebyteArray); //8位無符號整數數組ToBase64
//將數組轉換爲String字符傳
return strData;
}
/// <summary>
/// 將傳進來的二進制字符串轉換爲圖片文件
/// </summary>
/// <param name="path">保存的路徑</param>
/// <param name="Binary">需要轉換的字符串</param>
public static void BinaryToFile(string path,string Binary)
{
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
//利用新傳來的路徑實例化一個FileStream對象
BinaryWriter bw = new BinaryWriter(fs);
//實例化一個用於寫的 BinaryWriter
bw.Write(Convert.FromBase64String(Binary));
//將傳近來的二進制字符轉換爲8位無符號整數數組再寫進去
bw.Close(); //關閉二進制流寫入器
fs.Close(); //關閉文件流
}
}
(2)將文件轉換爲二進制及二進制轉換爲文件的實現(ToBinary.aspx):
public partial class toBinary : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string a=fileToData.FileToBinary(Server.MapPath("~/圖片1.gif")); //將圖片1轉換爲二進制
fileToData.BinaryToFile(Server.MapPath("~/圖片2.gif"), a); //將二進制轉換爲圖片2
}
}
(3)新建類:FileToxml.cs
加入命名空間:using System.IO;using System.Text;using System.Xml;
/// <summary>
/// 將文件轉換爲二進制
/// </summary>
public class FileToxml
{
public FileToxml()
{
}
/// <summary>
/// 從上傳控件中
/// </summary>
/// <param name="fu">被加載了文件的FileUpload上傳控件</param>
/// <param name="xmlPath">XML文件的存放位置</param>
/// <param name="id">圖片的標識ID</param>
public static void FileToXML(FileUpload fu,string xmlPath,Guid id)
{
if (fu.HasFile)
{ //先判斷FileUpload對象中是否包含了文件
string PathString = fu.FileName;
int FileLength = fu.PostedFile.ContentLength; //只得出帶擴展名的文件名
try
{
Byte[] FileByteArray = new byte[FileLenght];
//申明一個大小爲文件總字節大的Byte數組以存放即將產生的二進制數據
Stream Streamobj = fu.PostedFile.InputStream;
//創建一個能夠讀取被上載文件內容的Stream對象
Streamobj.Read(FileByteArray, 0, FileLength);
//使用Stream對象的讀取方法,參數說明將數據流存放在剛纔申明的數組中,從0開始讀,讀取的字節數爲全部
XmlDocument xdom = new XmlDocument();
if (!File.Exists(xmlPath))
{ //如果不存在XML,則創建
XmlDeclaration xdec = xdom.CreateXmlDeclaration("1.0", "utf-8", null);
xdom.AppendChild(xdec); //創建第一行聲明
XmlElement Root = xdom.CreateElement("File"); //創建根節點File
xdom.AppendChild(Root);
XmlElement RootElement = xdom.CreateElement("Image"); //創建父節點Image
Root.AppendChild(RootElement);
XmlElement childElementId = xdom.CreateElement("Guid"); //圖片標識字段
childElementId.InnerText = id.ToString();
//將傳近來的GUID編號作爲他的串聯值
RootElement.AppendChild(childElementId);
XmlElement childElementImgSize = xdom.CreateElement("size");//文件大小字段
childElementImgSize.InnerText = FileLength.ToString();
RootElement.AppendChild(childElementImgSize);
XmlElement childElementImgData = xdom.CreateElement("imgData"); //圖片信息
childElementImgData.InnerText = Convert.ToBase64String(FileByteArray);
//這句是關鍵,將上面的數組轉換爲字符串存起來
RootElement.AppendChild(childElementImgData);
xdom.Save(xmlPath);
//將上面創建的構架保存到指定的xml文件中
}
else
{ //如果XML文件存在的話就直接查找對應的節點,然後增加
xdom.Load(xmlPath); //加載xml文檔
//將指定的XML文件讀取到XMLdocument對象中
XmlNode root = xdom.SelectSingleNode("File");
//使用xpath表達式來查找到匹配條件的節點,我們這裏當然是指根節點了
XmlElement RootElement = xdom.CreateElement("Image");
root.AppendChild(RootElement);
//創建父節點
XmlElement childElementId = xdom.CreateElement("Guid");//圖片標識字段
childElementId.InnerText = id.ToString();//將傳近來的GUID編號作爲他的串聯值
RootElement.AppendChild(childElementId);
XmlElement childElementImgSize = xdom.CreateElement("size");
childElementImgSize.InnerText = FileLenght.ToString();//文件大小字段
RootElement.AppendChild(childElementImgSize);
XmlElement childElementImgData = xdom.CreateElement("imgData");
childElementImgData.InnerText = Convert.ToBase64String(fu.FileBytes);
RootElement.AppendChild(childElementImgData);
xdom.Save(xmlPath);
//將上面創建的構架保存到指定的xml文件中
}
}
catch (Exception e)
{
throw e;
}
}
}
}
(4)將圖像文件寫入到XML,再讀出來顯示或者還原(fileToxml.aspx):
public partial class fileToxml : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{//(上傳按鈕)將文件寫入XML中去
string xmlpath = Server.MapPath("~/App_Data/imgxml.xml");
Guid gid = Guid.NewGuid();
FileToxml.FileToXML(FileUpload1, xmlpath, gid);
Session["gid"] = gid;
}
protected void Button2_Click(object sender, EventArgs e)
{ //根據Gid索取圖片來顯示
ReadImgFromXml((Guid)Session["gid"]);
}
private void ReadImgFromXml(Guid gid)
{
XmlDocument xdom = new XmlDocument();
xdom.Load(Server.MapPath("~/App_Data/imgxml.xml"));
XmlNodeList xnl = xdom.SelectSingleNode(" //Image[Guid='" + gid.ToString() + "']").ChildNodes; //找出GUID=我們傳進來的ID的那一個節點的所有子節點
for (int i = 0; i < xnl.Count; i++)
{
string imgdata = xnl.Item(2).InnerText; //節點第三項imgdata
Response.OutputStream.Write(Convert.FromBase64String(imgdata), 0, imgdata.Length);
Response.End();//從0開始到指定的長度輸出打印所有的imgdata圖像信息
}
}
protected void Button3_Click(object sender, EventArgs e)
{ //從XML中讀出再轉換爲文件
XmlDocument xdom = new XmlDocument();
xdom.Load(Server.MapPath("~/App_Data/imgxml.xml"));
XmlNodeList xnl = xdom.SelectSingleNode(" //Image[Guid='" + Session["gid"].ToString() + "']" ).ChildNodes;
for (int i = 0; i < xnl.Count; i++)
{
string strData = xnl.Item(2).InnerText;
FileStream fs = new FileStream(Server.MapPath("~/圖像文件名.gif"), FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(Convert.FromBase64String(strData));
bw.Close();
fs.Close();
}
Image1.ImageUrl = "~/圖像文件名.gif";
}
}
(5)將圖像文件寫入到數據庫,再讀取出來顯示或者還原(ToData.aspx)
public partial class ToData : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Guid gid=Guid.NewGuid();
SqlConnection conn=new SqlConnection(ConfigurationManager.ConnectionStrings["數據源名稱"].ConnectionString);
conn.Open();
//注意:二進制不能採用字符串相加的方式寫入數據庫
SqlCommand cmd = new SqlCommand("Insert into img(gid,fileData) values(@gid ,@fileArray) ", conn); //新建一個表img,添加字段名gid,fileData,下面添加字段類型
cmd.Parameters.Add(" @gid", SqlDbType.UniqueIdentifier).Value = gid;
cmd.Parameters.Add(" @fileArray", SqlDbType.Image).Value = FileUpload1.FileBytes;
cmd.ExecuteNonQuery(); //執行SQL語句,返回影響行數
conn.Close();
Session["gid"] = gid; //保存gid的值
}
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["數據源名稱"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("select fileDat from img where gid='"+Session["gid"].ToString()+"'" , conn);
byte[] fbt=(byte[])cmd.ExecuteScalar();
conn.Close();
Response.OutputStream.Write(fbt, 0, fbt.Length);
Response.End();
}
}