Hi All,
I need a sample application for File Upload to SQL satabase.
I am using asp.net c#.net and sql server.
I am getting an error in Utilities class like this.
Please can anyone help me.
Server Error in '/' Application.
Incorrect syntax near '@Document'.
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: Incorrect syntax near '@Document'.
Source Error:
Line 68: cmd.Parameters["@Size"].Value = size;
Line 69: cmd.Parameters["@Document"].Value = fileData;
Line 70: cmd.ExecuteNonQuery();
Line 71:
Line 72: connection.Close();
Source File: C:\Users\CBS\documents\visual studio 2010\Projects\Mcases\Mcases\Utilities.cs Line: 70
Stack Trace:
Here is utilities.cs class
public static void SaveFile(string name, string contentType, int size, byte[] fileData)
{
using (SqlConnection connection = new SqlConnection())
{
OpenConnection(connection);
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandTimeout = 0;
string commandText = "INSERT INTO Document VALUES(@FileName, @ContentType,@Size,@Document)";
commandText = commandText + "@Document";
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@FileName", SqlDbType.VarChar);
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar, 50);
cmd.Parameters.Add("@size", SqlDbType.Int);
cmd.Parameters.Add("@Document", SqlDbType.VarBinary);
cmd.Parameters["@FileName"].Value = name;
cmd.Parameters["@ContentType"].Value = contentType;
cmd.Parameters["@Size"].Value = size;
cmd.Parameters["@Document"].Value = fileData;
cmd.ExecuteNonQuery();
connection.Close();
}
}
And this is my button click code to save file in Database
protected void btnUpload_Click(object sender, EventArgs e)
{
HttpFileCollection files = Request.Files;
foreach (string fileTagName in files)
{
HttpPostedFile file = Request.Files[fileTagName];
if (file.ContentLength > 0)
{
int size = file.ContentLength;
string name = file.FileName;
int position = name.LastIndexOf("\\");
name = name.Substring(position + 1);
string contentType = file.ContentType;
byte[] fileData = new byte[size];
file.InputStream.Read(fileData, 0, size);
Utilities.SaveFile(name, contentType, size, fileData);
}
}
}