Click here to Skip to main content
15,914,160 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was trying to upload image in ASP.NET web page and storing that in database.. I was en counted
with this error :(

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException:
String or binary data would be truncated.
The statement has been terminated.



Was using this coding:
C#
 if(FileUpload1.HasFile)
   {

      
       byte[] productImage = FileUpload1.FileBytes;

       SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringss"].ConnectionString);
       con1.Open();
       string cmdStr = ("INSERT INTO Reggg(im) VALUES(@im)");
       SqlCommand userExist = new SqlCommand(cmdStr, con1);
       userExist.Parameters.Add("@im", SqlDbType.VarBinary).Value = productImage;
       int result = Convert.ToInt32(userExist.ExecuteScalar().ToString());
         con1.Close();

       if (result > 0)
       {


           Label1.Text = "Product Saved Successfully";
       }
   }
          else
          {
              Label2.Text = "Please Select Product Image File";
          } 
}

Please help me to retrieve this.

[Edit]Code block added[/Edit]
Posted
Updated 3-Mar-13 6:55am
v3

1 solution

It is because of the line
C#
byte[] productImage = FileUpload1.FileBytes;


Instead refer - Upload images onto SQL Server using ASP.NET webpage[^]
C#
if (FileUpload1.PostedFile != null
&& FileUpload1.PostedFile.FileName != "")
{
      byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];

      HttpPostedFile Image = FileUpload1.PostedFile;
      Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

      SqlConnection myConnection = new SqlConnection("Data Source = ComputerName\\SQLEXPRESS; Initial Catalog= dbname; Integrated Security= SSPI");
      SqlCommand storeimage = new SqlCommand("INSERT INTO Image_Gallery "+"(Img_Id, Image_Content, Image_Type, Image_Size) "+" values (3, @image, @imagetype, @imagesize)", myConnection);

      storeimage.Parameters.Add("@image", SqlDbType.Image, myimage.Length).Value = myimage;

      storeimage.Parameters.Add("@imagetype", SqlDbType.VarChar, 100).Value = FileUpload1.PostedFile.ContentType;

      storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value = FileUpload1.PostedFile.ContentLength;

      myConnection.Open();
      storeimage.ExecuteNonQuery();
      myConnection.Close();

      Respone.Write("successfully upload the image");
}


Thanks...
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900