上传图片到SQLServer

英文源文档 <http://code.msdn.microsoft.com/Uploadedit-image-in-ASPNET-b96367a9>

翻译: 白水<dev.mjxy.cn>

代码下载: CSASPNETImageEditUpload.zip

 

 

此示例演示了在ASP.NET FormView中如何上传和显示图片,如何添加,编辑,删除和分页。

FormView默认显示了从数据库中取出的数据以及基本操作的界面

图片是从SQL Server 数据库中取出,并显示在网页上面。

实现步骤:

步骤1:在Visual Studio 中创建Web应用程序项目 CSASPNETFormViewUpload。

步骤2:拖拽FormView控件到Default.aspx页面。

(1) 重命名FormView为fvPerson。

(2) 在现在的代码中复制粘贴下面的模版标签:

ItemTemplate:重定义FormView的记录显示。

EditItemTemplate:自定义编辑视图

InsertItemTemplate:自定义插入视图

步骤3:从示例代码复制粘贴下面的方法到我们的项目文件Default.aspx.cs

Page_Load方法:当页面加载的时候初始化对象。

BindFormView方法:绑定FormView控件和SQL Server中的表。

步骤4:打开fvPerson的属性面板,切换到事件。双击下列事件生成事件处理程序。然后,按照示例所示代码完成事件处理程序。

(1) ModeChanging 事件:当FormView在Edit,Insert和ReadOnly模式之间切换时,重新绑定FormView控件,以便在新的模式下显示数据。

////////////////////////////////////////////////////////////////

    fvPerson.ChangeMode(e.NewMode);

    BindFormView();

    ////////////////////////////////////////////////////////////////

(2) PageIndexChanging事件:当单击翻页按钮的时候引发此事件。为了在新的页面显示的数据,我们需要设置新的一页的索引,然后重新绑定FormView控件。

////////////////////////////////////////////////////////////////   

    fvPerson.PageIndex = e.NewPageIndex;

    BindFormView();

    ////////////////////////////////////////////////////////////////

(3) ItemInserting 事件:当插入按钮被单击是引发,但是处理的是插入数据之前的操作。当单击按钮后,我们需要从InsertItemTemplate的FormView控件中获取first name,last name和指定图片文件(bytes)。

////////////////////////////////////////////////////////////////

    string strLastName = ((TextBox)fvPerson.Row.FindControl("tbLastName")).Text;

    string strFirstName = ((TextBox)fvPerson.Row.FindControl("tbFirstName")).Text;

    cmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 50).Value = strLastName;

    cmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = strFirstName;

    FileUpload uploadPicture = (FileUpload)fvPerson.FindControl("uploadPicture");

    if (uploadPicture.HasFile)

    {

        cmd.Parameters.Add("@Picture", SqlDbType.VarBinary).Value = uploadPicture.FileBytes;

    }

    else

    {

        cmd.Parameters.Add("@Picture", SqlDbType.VarBinary).Value = DBNull.Value;

    }

    ////////////////////////////////////////////////////////////////

(4) ItemUpdating 事件:当单击更新按钮的时候引发的事件。但是处理的是在更新数据之前的操作。当单击更新按钮后,我们需要从EditItemTemplate中的FormView控件获取和传递person ID,first name, last name和指定的图像文件(bytes)。

 ////////////////////////////////////////////////////////////////

    string strPersonID = ((Label)fvPerson.Row.FindControl("lblPersonID")).Text;   

    ////////////////////////////////////////////////////////////////

步骤5:创建一个新的ASP.NET Handle处理程序ImageHandler.ashx,用来处理从数据库中获取图片文件并输出到网页。

/// <summary>

    /// Connected to the DataBase,

    /// If the specific record has image,read out the specific row's

    /// image byte collection as well as image type, output it.

    /// If not, output the default image instead.

    /// </summary>

    public class ImageHandler : IHttpHandler

    {

        public void ProcessRequest(HttpContext context)

        {

            using (SqlCommand cmd = new SqlCommand())

            {

                cmd.Connection = new SqlConnection(

                    ConfigurationManager.ConnectionStrings["db_PersonsConnectionString"].ConnectionString);

                cmd.Connection.Open();

                cmd.CommandText = "select PersonImage,PersonImageType from tb_personInfo" +

                    " where id=" + context.Request.QueryString["id"];

                SqlDataReader reader = cmd.ExecuteReader(

                    CommandBehavior.CloseConnection | CommandBehavior.SingleRow);

                if (reader.Read())

                {

                    byte[] imgbytes = null;

                    string imgtype = null;

                    if (reader.GetValue(0) != DBNull.Value)

                    {

                        imgbytes = (byte[])reader.GetValue(0);

                        imgtype = reader.GetString(1);

                        // If bmp, convert to jpg and show because of the different formation type.

                        if (imgtype.Equals("image/bmp", StringComparison.OrdinalIgnoreCase))

                        {

                            using (MemoryStream ms = new MemoryStream(imgbytes))

                            {

                                using (Bitmap bm = new Bitmap(Image.FromStream(ms)))

                                {

                                    bm.Save(context.Response.OutputStream, ImageFormat.Jpeg);

                                }

                            }

                        }

                        else

                        {

                            context.Response.ContentType = imgtype;

                            context.Response.BinaryWrite(imgbytes);

                        }

                    }

                    else

                    {

                        imgbytes = File.ReadAllBytes(context.Server.MapPath

                            ("~/DefaultImage/DefaultImage.JPG"));

                        imgtype = "image/pjpeg";

                        context.Response.ContentType = imgtype;

                        context.Response.BinaryWrite(imgbytes);

                    }

                }

                reader.Close();

                context.Response.End();

            }

        }

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

原文链接:http://dev.mjxy.cn/a-Upload-images-to-SQLServer.aspx

posted @ 2011-07-24 09:17  敏捷学院  阅读(925)  评论(0编辑  收藏  举报