2010-09-16 37 views
1

如何在用户使用ASP.NET中的C#将图像文件上载到SQL Server 2005时动态插入图像?这是为了让用户在我的网络应用中上传他们的个人资料照片。与使用C#的Windows应用程序完成它有什么不同?将用户配置文件映像保存到数据库中

+1

你确定要插入数据库而不是将其上传到目录吗? – 2010-09-16 13:08:04

回答

1

与在WinForms中一样。获取byte[]image列。但我强烈建议使用文件系统来存储图片。 DB用于关系数据,文件系统用于原始字节。

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

+1

是的,我同意安德烈,如果你正在做的是试图存储用户个人资料图片,上传他们的目录并存储他们的来源。想象一下从数据库查询大量的用户个人资料图片......你会有巨大的表现点击! – 2010-09-16 13:37:56

0

下面是在C#中将图像插入数据库的代码示例。你会粗糙的需要支持表的图片应该是一个字节字段,并保持图片类型,以便您可以稍后检索图像来显示它。除此之外,您需要将文件输入框与提交按钮一起放在页面上。

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!"; 
    } 

}