2013-03-15 50 views
5

我已經創建了將映像上載到SQL Server的代碼。嘗試將映像保存到SQL Server時出錯

這裏是將圖像轉換成字節代碼:

//Use FileInfo object to get file size. 
FileInfo fInfo = new FileInfo(p);   

//Open FileStream to read file 
FileStream fStream = new FileStream(p, FileMode.Open, FileAccess.Read); 
byte[] numBytes = new byte[fStream.Length]; 
fStream.Read(numBytes, 0, Convert.ToInt32(fStream.Length)); 

//Use BinaryReader to read file stream into byte array. 

//BinaryReader br = new BinaryReader(fStream); 

//When you use BinaryReader, you need to supply number of bytes to read from file. 
//In this case we want to read entire file. So supplying total number of bytes. 

// data = br.ReadBytes((int)numBytes); 
return numBytes; 

這裏是字節添加到SqlCommand參數作爲值碼:

objCmd.Parameters.Add("@bill_Image", SqlDbType.Binary).Value = imageData; 
    objCmd.ExecuteNonQuery(); 

但我得到錯誤

字符串或二進制數據將被截斷。聲明已被終止

我該如何克服這個問題?

+7

SQL Server中的列大小是什麼?該錯誤基本上告訴您,您正在嘗試存儲比列中允許的更多字節。 – Icarus 2013-03-15 13:39:51

+0

如果你的列長度已經是'max',那麼檢查表中是否有觸發器? – 2013-03-15 13:42:03

+0

我已經將列更改爲Max,並且我沒有使用表中的觸發器 – jeevacl 2013-03-15 15:01:52

回答

4

錯誤很明顯地表明您正在嘗試保存字段定義所允許的更多字節。

不知道你用於bill_Image的sql類型,但是用於存儲圖像的相關字段定義是varbinary(MAX)

+0

您好我已更改代碼,如objCmd.Parameters.Add(「@ bill_Image」,SqlDbType.VarBinary,-1).Value = imageData;並仍然得到相同的錯誤。 – jeevacl 2013-03-15 14:05:40

+0

,我也與objCmd.Parameters.Add(「@ bill_Image」,SqlDbType.VarBinary).Value = imageData;但仍然得到了同樣的錯誤 – jeevacl 2013-03-15 14:06:41

+0

@jeevacl:你可以發佈你'bill_Image'的sql字段定義嗎? – 2013-03-15 14:08:16

0

檢查數據庫中bill_Image列的定義。

它應該像

bill_Image varbinary(X) 

只是增加X或放在那裏MAX,而不是一個號碼(如果你有超過8個000字節的圖像)

信息關於二進制/ VARBINARY類型here

+0

根據您的建議進行了所有更改,並且仍然出現相同的錯誤... \ – jeevacl 2013-03-15 14:07:49

+0

@jeevacl您是否有任何其他字段設置了該請求?這個錯誤只是表示某些字段的長度小於您要輸入的數據的長度。此外,您的圖像的大小是多少? – 2013-03-15 14:10:05

+0

圖片尺寸爲858kb。它是窗口示例圖像 – jeevacl 2013-03-15 14:12:26