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

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

       索引:图片   存储     Sql Server数据库

       进行Web开发时,时常需要上传图片,许多前辈及经验都告诉我们应该上传到一个目录,将地址写如数据库云云,无可否认这是通用的方法,并且容易维护。但有时我们仍然需要将图片存储到数据库中,也许就是为了安全。


        在这篇文章中,我们将通过一个示例来说明将图片存储到sql server 2005中的方法及过程。
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: &nbsp; &nbsp;&nbsp;
        <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。
      

      如果对以上方法有疑虑可以参考MSDN:http://msdn2.microsoft.com/zh-cn/library/system.io.aspx
对于如何将图片从数据库中读取并显示于页面中,将在下一篇文章中讲解。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值