zoukankan      html  css  js  c++  java
  • 在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
    对于如何将图片从数据库中读取并显示于页面中,将在下一篇文章中讲解。

  • 相关阅读:
    10: Django + Uwsgi + Nginx 的生产环境部署
    04:应用管理
    发送消息的时候,会指定用户,其实还可以定义媒介为脚本,让用户执行这个脚本
    解决zabbix使用中文是出现乱码的问题
    inotify 工具 是一种强大的、细粒度的、异步文件系统监控机制
    rsync 远程同步工具
    vsftpd:非常安全的ftp服务端程序
    Varnish是一款高性能的开源HTTP加速器
    keepalived 高可用(IP飘移)
    dns域名解析
  • 原文地址:https://www.cnblogs.com/no7dw/p/1720873.html
Copyright © 2011-2022 走看看