您的位置:首页 > 数据库

C#以二制的方式同时存储文字和图片到sqlserver,并读取

2010-05-16 15:08 501 查看
前一段时间,公司有这个需求,然后呢,我就找了找相关的一些资料。

结果没有找到,然后有一次和女友一起出去散步,突然想到了这种方法。然后回来试了下,的确可以实现。

但是呢,很很多地方都需要改进,我这里只是拿出一个粗糙的实现而已。还请网友们多多指教。

不说废话了,贴代码吧。

前台代码:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
请输入你所想保存的文字:<asp:TextBox ID="TextBox1" runat="server" Width="216px"></asp:TextBox><br />
请选择需要保存的文件:
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
请选择要输出的格式:
<asp:DropDownList ID="DropDownList1" runat="server" Width="222px">
<asp:ListItem>text/html</asp:ListItem>
<asp:ListItem>text/plain</asp:ListItem>
<asp:ListItem>image/gif</asp:ListItem>
<asp:ListItem>image/jpeg</asp:ListItem>
<asp:ListItem>image/tiff</asp:ListItem>
<asp:ListItem>application/msword</asp:ListItem>
<asp:ListItem>application/tiff</asp:ListItem>
<asp:ListItem>application/x-excel</asp:ListItem>
<asp:ListItem>application/ms-powerpoint</asp:ListItem>
<asp:ListItem>application/pdf</asp:ListItem>
<asp:ListItem>application/zip</asp:ListItem>
</asp:DropDownList>
<br />
<asp:Button ID="btnSave" runat="server" Text="保存" OnClick="btnSave_Click" />
<asp:Button ID="btnRead" runat="server" Text="读取" OnClick="btnRead_Click" /> <br />
<asp:Image ID="Image1" ImageUrl="~/Temp/aa.gif" runat="server" /></div>

</form>
</body>
</html>


后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Drawing;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSave_Click(object sender, EventArgs e)
{
if (this.TextBox1.Text.Trim() == string.Empty)
{
Response.Write("<mce:script type="text/javascript"><!--
alert('必须输入不允许为空');
// --></mce:script>");
return;
}
if (this.FileUpload1.FileContent.Length == 0)
{
Response.Write("请选择需要导入的文件");
return;
}
byte[] contents1 = ConvertToByte(this.TextBox1.Text.Trim());
//定义变量获取一个文件
byte[] contents2 = this.FileUpload1.FileBytes;
int len = contents1.Length + contents2.Length;
byte[] contents = new byte[len];
int k = 0;
for (int i = 0; i < len; i++)
{
if (i < contents1.Length)
{
contents[i] = contents1[i];
}
else
{

contents[i] = contents2[k];
k++;
}
}
string typeLength = contents1.Length + ";" + contents2.Length;
string types = "text/html;image/gif";//我这里写的是个死的,仅仅是为了测试向数据库中插入图片和文字
//插入数据库
InsertBytesValue(contents, typeLength, types);
}
protected void btnRead_Click(object sender, EventArgs e)
{
byte[] testStr = ConvertToByte("测试文字和图片哦。呵呵。");
string connStr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
string cmdStr = "select top 1 * from test1 where proContent is not null order by [id] desc";
SqlDataAdapter sda = new SqlDataAdapter(cmdStr, conn);
DataSet ds = new DataSet();
sda.Fill(ds);
string str = string.Empty;
foreach (DataRow dr in ds.Tables[0].Rows)
{
byte[] contents = (byte[])dr["proContent"];//所有的二进制流

string typeLength=dr["typeLength"].ToString();//不同类型的二进制长度
string types = dr["types"].ToString();//不同类型的二进制的类型集合
if (typeLength.IndexOf(';') == -1)
{
byte[] newContents = contents;
Response.ContentEncoding = System.Text.UTF8Encoding.Default;
Response.ContentType = this.DropDownList1.SelectedItem.Text;
Response.BinaryWrite(contents);
}
else
{
//类型的个数
int typeCount = typeLength.Split(new char[] { ';' }).Length - 1;
for (int i = 0; i < typeCount; i++)
{
string type0 = types.Split(new char[]{';'})[i];
int len0 = int.Parse(typeLength.Split(new char[]{';'})[i]);
byte[] part0 = new byte[len0];
byte[] part1 = new byte[(contents.Length-len0)];
int k = 0;
for (int j = 0; j < contents.Length; j++)
{
if (j < len0)
{
part0[j] = contents[j];
}
else
{

part1[k] = contents[j];
k++;
}
}
string res = string.Empty;
res = ConvertToString(part0);
MemoryStream ms = new MemoryStream();
ms.Write(part1, 0, part1.Length);
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms);
string path = AppDomain.CurrentDomain.BaseDirectory + "Temp//";
string fileName = DateTime.Now.ToString("yyyyMMddhhmmss")+".gif";
string filePath = path + fileName;
bmp.Save(filePath);
res += "<img src="/" mce_src="/""Temp/"+fileName+"/"/>";
Response.Write(res);

}
//Response.Write(str);
}
catch (Exception ex)
{
Response.Write(ex.Message);
throw;
}
finally
{
conn.Close();
}
}

//二进制转字符串:
private string ConvertToString(byte[] thebyte)
{
char[] Chars = new char[System.Text.Encoding.Default.GetCharCount(thebyte, 0, thebyte.Length)];
System.Text.Encoding.Default.GetChars(thebyte, 0, thebyte.Length, Chars, 0);
string newString = new string(Chars);
return newString;
}

//字符串转二进制:
private byte[] ConvertToByte(string theString)
{
byte[] byteStream = System.Text.Encoding.Default.GetBytes(theString);
return byteStream;
}

/// <summary>
/// 向数据库中拷入二进制数据的方法
/// </summary>
/// <param name="contents">二进制数组</param>
/// <param name="typeLength">不同类型二进制数据的长度(以分号分隔)</param>
/// <param name="types">不同类型二进制数据类型(以分号分隔)</param>
private void InsertBytesValue(byte[] contents,string typeLength,string types)
{
string connStr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
try
{
conn.Open();
string cmdStr = "insert into test1(proContent,typeLength,types) values(@para1,@para2,@para3)";
SqlCommand cmd = new SqlCommand(cmdStr, conn);
cmd.Parameters.Add("@para1", SqlDbType.Image);
cmd.Parameters.Add("@para2",SqlDbType.VarChar,1000);
cmd.Parameters.Add("@para3", SqlDbType.VarChar, 1000);

//byte[] contents = ConvertToByte("测试一下子");
cmd.Parameters["@para1"].Value = contents;
cmd.Parameters["@para2"].Value = typeLength;
cmd.Parameters["@para3"].Value = types;
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
Response.Write("<mce:script type="text/javascript"><!--
alert('数据保存成功');
// --></mce:script>");
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
throw;
}
finally
{
conn.Close();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: