Click here to Skip to main content
15,035,283 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hello every one I use the code to upload photo to data base :

// Read the file and convert it to Byte Array
       string filepath = upload_image.PostedFile.FileName;
       string filename = Path.GetFileName(filepath);
       string ext = Path.GetExtension(filename);
       string contenttype = string.Empty;

       switch (ext){
           case ".doc":
               contenttype = "application/vnd.ms-word";
               break;
           case ".docx":
               contenttype = "application/vnd.ms-word";
               break;
           case ".xls":
               contenttype = "application/vnd.ms-excel";
               break;
           case ".xlsx":
               contenttype = "application/vnd.ms-excel";
               break;
           case ".jpg":
               contenttype = "image/jpg";
               break;
           case ".png":
               contenttype = "image/png";
               break;
           case ".gif":
               contenttype = "image/gif";
               break;
           case ".pdf":
               contenttype = "application/pdf";
               break;
       }
       if (contenttype != String.Empty)
       {
           Stream fs = upload_image.PostedFile.InputStream;
           BinaryReader br = new BinaryReader(fs);
           Byte[] bytes = br.ReadBytes((Int32)fs.Length);
           SqlConnection conn = new SqlConnection("Data Source=DESKTOP-06QKCFT\\SQLEXPRESS;Initial Catalog=CMS1;Integrated Security=True");
           conn.Open();

           string insert_query = "INSERT INTO [image] ([name], [contenttype], [data]) VALUES (@name, @contenttype, @data)";
           SqlCommand cmd = new SqlCommand(insert_query, conn);

           cmd.Parameters.AddWithValue("@name", SqlDbType.VarChar).Value = filename;
           cmd.Parameters.AddWithValue("@contenttype", SqlDbType.VarChar).Value = contenttype;
           cmd.Parameters.AddWithValue("@data", SqlDbType.VarChar).Value = bytes;
           cmd.ExecuteNonQuery();
           Lb1.ForeColor = System.Drawing.Color.Green;
           Lb1.Text = "File Uploaded Successfully";
           conn.Close();
       }
       else
       {
           Lb1.ForeColor = System.Drawing.Color.Red;
           Lb1.Text = "File format not recognised." +
         " Upload Image/Word/PDF/Excel formats";

       }

   }


What I have tried:

but when I run it gave me this error: the error in line 66
Line 64:             cmd.Parameters.AddWithValue("@contenttype", SqlDbType.VarChar).Value = contenttype;
Line 65:             cmd.Parameters.AddWithValue("@data", SqlDbType.VarChar).Value = bytes;
Line 66:             cmd.ExecuteNonQuery();
Line 67:             Lb1.ForeColor = System.Drawing.Color.Green;
Line 68:             Lb1.Text = "File Uploaded Successfully";
Posted
Updated 11-Apr-17 0:49am
Comments
CHill60 11-Apr-17 6:40am
   
What is the error?
MuhammadNaamh 11-Apr-17 6:55am
   
Line 66: cmd.ExecuteNonQuery();
CHill60 11-Apr-17 6:57am
   
That is not an error. That is a line of code.
Richard MacCutchan 11-Apr-17 6:58am
   
How the hell do these people get jobs?
CHill60 11-Apr-17 7:01am
   
I know :sigh:
MuhammadNaamh 11-Apr-17 7:05am
   
I am beginner in c# not professional like you #Richard MacCutchan#
CHill60 11-Apr-17 7:07am
   
A friendly piece of advice if you need to ask more questions: We will need to know the wording of the error messages that are shown. Exact wording is best and you can usually use Ctrl-C to copy it. Giving us all the relevant information helps us to help you.
MuhammadNaamh 11-Apr-17 7:11am
   
I'll do thanks
Richard MacCutchan 11-Apr-17 7:12am
   
You have been a member here for 5 years; hardly a beginner.
MuhammadNaamh 11-Apr-17 7:20am
   
can you help give a solution say it other than that thanks for watching
Richard MacCutchan 11-Apr-17 6:57am
   
That is not an error, it is a C# statement.

1 solution

I think I've just spotted the problem...
C#
cmd.Parameters.AddWithValue("@name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.AddWithValue("@contenttype", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.AddWithValue("@data", SqlDbType.VarChar).Value = bytes;
You've mixed up Parameters.Add and Parameters.AddWithValue
Either use
C#
cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@contenttype", SqlDbType.VarChar).Value = contenttype;
cmd.Parameters.Add("@data", SqlDbType.VarChar).Value = bytes;
or better...
C#
cmd.Parameters.AddWithValue("@name", filename);
cmd.Parameters.AddWithValue("@contenttype", contenttype);
cmd.Parameters.AddWithValue("@data", bytes);
   
Comments
MuhammadNaamh 11-Apr-17 7:02am
   
thanks it's worked the error stop :) but the table in DB is empty !!!! the message show the File Uploaded Successfully but no data!!!
CHill60 11-Apr-17 7:15am
   
You can check the return value from cmd.ExecuteNonQuery() - it should be the number of rows affected by the query - in this case you would expect it to be 1.
If there are no errors being thrown are you sure that the database you are looking at for the record is the same one as the connection in the code? (I've done this before when I've had tables in two different databases with the same name, and I've been looking at the wrong one!)
I presume you are using .NET Framework 2.0 or later? (i.e. not 1.0)
The only other thing I can think of without an error message to help is that the table does not allow NULLs in one of the columns and that one of your values is actually NULL. You can debug to check that - see this article for help with that Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
MuhammadNaamh 11-Apr-17 7:30am
   
I changed the way :
private Boolean update_image(SqlCommand cmd)
{
String strConnString = System.Configuration.ConfigurationManager
.ConnectionStrings["CMS1ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}

}
protected void upload_Click(object sender, EventArgs e)
{
// Read the file and convert it to Byte Array
string filepath = upload_image.PostedFile.FileName;
string filename = Path.GetFileName(filepath);
string ext = Path.GetExtension(filename);
string contenttype = string.Empty;

switch (ext){
case ".doc":
contenttype = "application/vnd.ms-word";
break;
case ".docx":
contenttype = "application/vnd.ms-word";
break;
case ".xls":
contenttype = "application/vnd.ms-excel";
break;
case ".xlsx":
contenttype = "application/vnd.ms-excel";
break;
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
break;
case ".pdf":
contenttype = "application/pdf";
break;
}
if (contenttype != String.Empty)
{
Stream fs = upload_image.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);

//insert the file into database
string insert_query = "INSERT INTO [image] ([name], [contenttype], [data]) VALUES (@name, @contenttype, @data)";
SqlCommand cmd = new SqlCommand(insert_query);

cmd.Parameters.AddWithValue("@name", filename);
cmd.Parameters.AddWithValue("@contenttype", contenttype);
cmd.Parameters.AddWithValue("@data", bytes );
update_image(cmd);
Lb1.ForeColor = System.Drawing.Color.Green;
Lb1.Text = "File Uploaded Successfully";

}
else
{
Lb1.ForeColor = System.Drawing.Color.Red;
Lb1.Text = "File format not recognised." +
" Upload Image/Word/PDF/Excel formats";

}

}
}
it show me message (String or binary data would be truncated. The statement has been terminated.)
File Uploaded Successfully
MuhammadNaamh 11-Apr-17 7:32am
   
but no data also :(
CHill60 11-Apr-17 7:46am
   
That means that one of the values you are trying to insert into the table is too big for the column. ... [EDIT - removed the incorrect thoughts. Sorry].
How have you declared the columns of the database table
MuhammadNaamh 11-Apr-17 7:55am
   
yes my table name is image :

id int
name varchar(255)
contenttype varchar(255)
data varbinary(255)
CHill60 11-Apr-17 8:00am
   
That will be the data varbinary(255) column - the column is not big enough for the data you are trying to insert. Shouldn't that be of type image
MuhammadNaamh 11-Apr-17 9:02am
   
Thanks for your time it worked 100% that is great to know a person like you
Richard Deeming 11-Apr-17 12:08pm
   
With the Add version, you'd also need to correct the type of the @data parameter - SqlDbType.VarChar isn't going to work for binary data. :)

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