Start New Discussion within our Web Development Community

Hi Guys

Could you please provide me with the code that will upload a file using C# and save it in SQL, I have searched through the internet with no luck at all

Thanks in Advance

Try the code below:

<%@ Page Language="c#" AutoEventWireup="false"%>
<%
	try
	{
		int iFileLength;
		HttpFileCollection files = HttpContext.Current.Request.Files;
		HttpPostedFile uploadfile = files["RemoteFile"];
		String strImageName = uploadfile.FileName;
	    
		iFileLength = uploadfile.ContentLength;
		Byte[] inputBuffer = new Byte[iFileLength];
		System.IO.Stream inputStream;
		inputStream = uploadfile.InputStream;
		inputStream.Read(inputBuffer,0,iFileLength);
	    
	    String strConnString = "Data Source=MYPC\\SQLEXPRESS;Initial Catalog=WebTwain;User ID=sa;Pwd=sa;";
    
		System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(strConnString);

		String SqlCmdText = "INSERT INTO tblImage (strImageName,imgImageData) VALUES (@ImageName,@Image)";
		System.Data.SqlClient.SqlCommand sqlCmdObj = new System.Data.SqlClient.SqlCommand(SqlCmdText, sqlConnection);

		sqlCmdObj.Parameters.Add("@Image",System.Data.SqlDbType.Binary,iFileLength).Value = inputBuffer;
		sqlCmdObj.Parameters.Add("@ImageName",System.Data.SqlDbType.VarChar,255).Value = strImageName;

		sqlConnection.Open();
		sqlCmdObj.ExecuteNonQuery();
		sqlConnection.Close();
	}
	catch(System.Data.SqlClient.SqlException e)
	{
	}		
%>

Thanks,

Comments
Very Helpful

Hi

Thanks a lot man for the code, much appreciated but now I am getting an error, its not writing at all in the SQL, the error is: Object reference not set to an instance of an object. I have tried to check what variables not declared and all but with no lucky, Im a novice in ASP.Net

Below is the code
Can u check if there is anything wrong, thanks

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["StringConn"].ToString()))
        {
            try
            {
                int iFileLength;
                HttpFileCollection files = HttpContext.Current.Request.Files;
                HttpPostedFile uploadfile = files["RemoteFile"];
                String strFileName = uploadfile.FileName;
                iFileLength = uploadfile.ContentLength;
                Byte[] inputBuffer = new Byte[iFileLength];
                System.IO.Stream inputStream;
                inputStream = uploadfile.InputStream;
                inputStream.Read(inputBuffer,0,iFileLength);

                conn.Open();
                SqlCommand cmd = new SqlCommand("sp_AddTasks", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter daAddTask = new SqlDataAdapter(cmd);

                cmd.Parameters.AddWithValue("@TaskName", txtTaskName0.Text);
                cmd.Parameters.AddWithValue("@Priority", ddlPriority.Text);
                cmd.Parameters.AddWithValue("@DateCreated", lblDateSubmitted.Text);
                cmd.Parameters.AddWithValue("@DueDate", dtDueDate.Text);
                cmd.Parameters.AddWithValue("@Status", ddlStatus0.Text);
                cmd.Parameters.AddWithValue("@AssignedTo", ddlAssignedto.Text);
                cmd.Parameters.AddWithValue("@Owner", ddlOwner.Text);
                cmd.Parameters.AddWithValue("@Notes", txtAreaNotes.Value.ToString());
                cmd.Parameters.Add("@AttachmentName", System.Data.SqlDbType.VarChar, 255).Value = strFileName; 
                cmd.Parameters.Add("@Attachment", System.Data.SqlDbType.VarBinary, iFileLength).Value = inputBuffer;
                cmd.Parameters.AddWithValue("@TaskType", ddlTaskType.Text);

                cmd.ExecuteNonQuery();
                Console.WriteLine("Record Added");
                conn.Close();
            }
            catch(System.Data.SqlClient.SqlException error)
            {
                lblError.Text = error.Message;
            }
            finally
            {
                conn.Close();
            }
        }

And one more thing, my attachment field is not loading on the Datagrid

Attachment varbinary(max),

Hi Guys

Could you please provide me with the code that will upload a file using C# and save it in SQL, I have searched through the internet with no luck at all

Thanks in Advance

you cant store whole file in database.
one solution is to save the location of file in the database. so that when needed with the help of that path you can retrieve it.

you cant store whole file in database.
one solution is to save the location of file in the database. so that when needed with the help of that path you can retrieve it.

And how do you do that?

This article has been dead for over six months. Start a new discussion instead.