如何将图像插入数据库?

时间:2011-07-02 11:49:48

标签: c# asp.net sql

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();
    }
}

如何将streamreader而不是Filestream reader放入数据库?

1 个答案:

答案 0 :(得分:1)

这是另一篇文章:

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

然而,普遍的共识是,最好将图像存储在文件系统中。

相关问题