Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while trying to save an image into SQL Server

Tags:

c#

sql-server

I have created code to upload an image into SQL Server.

Here is the code to convert the image into bytes:

//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;

And here is the code to add the bytes to a SqlCommand parameter as values:

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

But I am getting error

String or binary data would be truncated. The statement has been terminated

How can I overcome this problem?

like image 349
jeevacl Avatar asked Oct 05 '22 17:10

jeevacl


1 Answers

Error is clearly indicating that you're trying to save more bytes than allowed by the field definition.

Not sure what sql type you're using for bill_Image but an appropiated field definition to store an image would be varbinary(MAX).

like image 188
Claudio Redi Avatar answered Oct 07 '22 06:10

Claudio Redi