开发者

How do I insert an image into a database?

public void InsertAnImage(Guid i)
{
    StringBuilder sb = new StringBuilder();

    sb.Append("");

    Stream stream = FileUpload1.FileContent;
    StreamReader reader = new StreamReader(stream);

    string myConnectionString = AllQuestionsPresented.connectionString;
    using (SqlConnection conn = new SqlConnection(AllQuestionsPresented.connectionString))
    {
        // sample query with parameters to insert into db
        string sqlQuery = "INSERT INTO [UserProfile] (UserID, Picture) Values (@userId, @picture)";
        // conn is your db connection
        SqlCommand command = new SqlCommand(sqlQuery, conn);
        // creating parameters
        SqlParameter paramId = new SqlParameter("@userId", SqlDbType.Int, 4);
        paramId.Value = 45;
        // you picture parameter, and assigning its the value
        SqlParameter paramPicture = new SqlParameter("@picture", SqlDbType.Binary, myImage.Length);// red line here
        paramPicture.Value = myImage;// red line here
        // adding params to command
        command.Parameters.Add(paramId);
        command.Parameters.Add(paramPicture);
    开发者_运维技巧    // then execute your command
        command.ExecuteNonQuery();
    }
}

How do I put a streamreader instead of Filestream reader to the database?


Here's another article:

Save and Retrieve Images from the Database using ASP.NET 2.0 and ASP.NET 3.5

However, the general consensus is that it's better to store the image in the file system.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜