您的位置:首页 > 编程语言 > ASP

在ASP.NET中将图片存储到Sql Server数据库中

2011-09-21 19:47 288 查看
1:创建aspx页面。

在这一步,我们需要一个FileUpload控件,同时最重要的是需要将Form的enctype属性设置为multipart/form-data。该FileUpload控件ID为:fileuploadPic。其HTML源码如下所示:

<form id="form1" runat="server" enctype="multipart/form-data">

<div>

You must select the picture:     

<asp:FileUpload ID="fileuploadPic" runat="server" />

<br /><br />

<asp:Button ID="btnOk" runat="server" Text="Click here to upload the picture" OnClick="btnOk_Click" />

<br />

<br />

<br />

<asp:Label ID="lblInfor" runat="server" Text="Label"></asp:Label>

</div>

</form>

2:创建数据库test。

在数据库test中,我们创建了一个imgtest数据表,其属性字段如下所示:

id,主键、自动编号;info,varchar(50),用来存储上传图片的格式;img,Image类型,用来存储图片的二进制格式数据。

3:编写btnOk_Click事件,完成图片的上传工作。

其具体编码如下所示:

using System.Data;

using System.Data.SqlClient;

using System.IO;

protected void btnOk_Click(object sender, EventArgs e)

{

//判断上传格式是否符合

bool flag = false;

if (fileuploadPic.HasFile)

{

string fileExtension = Path.GetExtension(fileuploadPic.FileName).ToUpper();

//只允许上传格式

string[] allowExtension = { ".JPG",".GIF",".PNG" };

for (int i = 0; i < allowExtension.Length; i++)

{

if (fileExtension == allowExtension[i])

flag = true;

}

}

//上传

if (flag)

{

int imgSize;

string imgType;

Stream imgStream;

imgSize = fileuploadPic.PostedFile.ContentLength;

imgType = fileuploadPic.PostedFile.ContentType;

imgStream = fileuploadPic.PostedFile.InputStream;

byte[] imgContent = new byte[imgSize];

imgStream.Read(imgContent, 0, imgSize);

imgStream.Close();

//connection

string strConn = "server=localhost\\sqlexpress;database=test;user id=sa;password=sa123";

SqlConnection conn = new SqlConnection(strConn);

SqlCommand comm = conn.CreateCommand();

string sql = "insert into imgtest(info,img) values(@info,@img)";

comm.CommandText = sql;

comm.Parameters.Add("@info", SqlDbType.VarChar, 50);

comm.Parameters.Add("@img", SqlDbType.Image);

comm.Parameters["@info"].Value = imgType;

comm.Parameters["@img"].Value = imgContent;

try

{

conn.Open();

comm.ExecuteNonQuery();

conn.Close();

lblInfor.Text = "图片上传成功!";

}

catch (Exception ex)

{

lblInfor.Text = "Error:" + ex.ToString();

}

}

else

{

lblInfor.Text = "文件格式不正确,请检查...";

}

}

4:在上述代码中,我们限定只允许上传三种格式的图片:jpg、gif及png,这样将最大限度地减少错误的发生。

说明:

首先使用fileuploadPic.PostedFile.ContentLength获取图片的大小。

使用fileuploadPic.PostedFile.ContentType获取图片的格式。

使用fileuploadPic.PostedFile.InputStream获取了一个InputStream流。

最后使用imgStream.Read(imgContent, 0, imgSize)方法将图片读入到字节数组中,之后的工作就是一件普通的写入数据库的操作。该方法原型为Read(byte[] buffer,int offset,int count),读入buffer,从offset开始读取count个字节数。

注意在comm.Parameters.Add("@img", SqlDbType.Image)一步,需要将img的参数类型设置为SqlDbType.Image。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: