可能重複:
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控件從用戶獲取圖像以保存在數據庫中? –