可能重复:
Upload images to SQL Server 2005 using ASP.Net MVC?如何在sql server中存储图像?
我要寻找一个代码示例通过一个asp.net MVC应用程序到SQL Server存储图像?我找不到使用FileStream选项的工作代码应用程序的示例?
可能重复:
Upload images to SQL Server 2005 using ASP.Net MVC?如何在sql server中存储图像?
我要寻找一个代码示例通过一个asp.net MVC应用程序到SQL Server存储图像?我找不到使用FileStream选项的工作代码应用程序的示例?
// Read image file from a file
FileStream stream = new FileStream("pathToFile", FileMode.Open);
// convert to byte array to save in db
byte[] myImage = new byte[stream.Length];
stream.Read(myImage, 0, myImage.Length);
// 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);
paramPicture.Value = myImage;
// adding params to command
command.Parameters.Add(paramId);
command.Parameters.Add(paramPicture);
// then execute your command
command.ExecuteNonQuery();
只是好奇 - 为什么? – zerkms
您是否使用FileUpload控件从用户获取图像以保存在数据库中? –