开发者

save user profile image to database

How can I dynamically insert images when user uploads an image f开发者_如何学Cile to SQL Server 2005 with C# in ASP.NET? This is to let users upload their profile photos in my web app. Is it very different from how it is done for windows app with C#?


There is a metric ton of examples on the web on this one:

http://aspalliance.com/138
https://web.archive.org/web/20210304133428/https://www.4guysfromrolla.com/articles/120606-1.aspx
http://www.aspfree.com/c/a/ASP.NET/Uploading-Images-to-a-Database--C---Part-I/

You should be able to follow any of those to accomplish what you want.


The same way as in in WinForms. Get byte[] and same to image column. But i strongly recommend to use file system to store pictures. DB is for relational data, File System for raw bytes.

http://msdn.microsoft.com/en-us/library/aa479405.aspx


Here is a sample of the code behind for inserting an image into a database in C#. You will of coarse need supporting table the picture should be a byte field and keep the picture type so you can retrieve the image later to display it. In addition to that you need to put a file input box on your page along with a submit button.

public void AddImage(object sender, EventArgs e)
{

    int intImageSize;

    String strImageType;
    Stream ImageStream;
    FileStream fs = File.OpenRead(Request.PhysicalApplicationPath + "/Images/default_image.png");
    Byte[] ImageContent;

    if (PersonImage.PostedFile.ContentLength > 0)
    {
        intImageSize = PersonImage.PostedFile.ContentLength;
        strImageType = PersonImage.PostedFile.ContentType;
        ImageStream = PersonImage.PostedFile.InputStream;

        ImageContent = new Byte[intImageSize];
        int intStatus;
        intStatus = ImageStream.Read(ImageContent, 0, intImageSize);
    }
    else
    {
        strImageType = "image/x-png";
        ImageContent = new Byte[fs.Length];
        fs.Read(ImageContent, 0, ImageContent.Length);
    }

    SqlConnection objConn = new SqlConnection(ConfigurationManager.AppSettings["conn"]);
    SqlCommand objCmd;
    string strCmd;

    strCmd = "INSERT INTO ImageTest (Picture, PictureType) VALUES (@Picture, @PictureType)";

    objCmd = new SqlCommand(strCmd, objConn);

    SqlParameter prmPersonImage = new SqlParameter("@Picture", SqlDbType.Image);

    prmPersonImage.Value = ImageContent;

    objCmd.Parameters.Add(prmPersonImage);
    objCmd.Parameters.AddWithValue("@PictureType", strImageType);

    lblMessage.Visible = true;

    try
    {
        objConn.Open();
        objCmd.ExecuteNonQuery();
        objConn.Close();
        lblMessage.Text = "ImageAdded!";
    }
    catch
    {
        lblMessage.Text = "Error occured the image has not been added to the database!";
    }

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜