Hi, I have a need to insert images to the database.

I tried it using the following code:

if ((file1.PostedFile != null) && (file1.PostedFile.ContentLength > 0))


// Get the filename.

byte[] fileData = null;

string fn = System.IO.Path.GetFileName(file1.PostedFile.FileName);



// Access the file stream and begin the upload. Store the file in a memory byte array.

Stream MyStream = file1.PostedFile.InputStream;

long iLength = MyStream.Length;

fileData = new byte[(int)MyStream.Length];

MyStream.Read(fileData, 0, (int)MyStream.Length);


clsConns obj1=new clsConns();



catch (Exception excep)





But some invalid byte values are stored on the database.

I used Visual studio2005 and sqlserver2000.

Can I get the correct method for inserting images to the database.

Thanks in advance.

You can do it like this (A simple example)

int len = FileUpload1.PostedFile.ContentLength;

            byte[] pic = new byte[len];
            FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
            string fup = FileUpload1.PostedFile.FileName;

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dev"].ToString());
            SqlCommand cmd = new SqlCommand("insert into test(name,pic) values (@name,@pic)", conn);
            cmd.Parameters.AddWithValue("@name", fup);
            cmd.Parameters.AddWithValue("@pic", pic);

Hope this Help

I tried this method.But the image stored as bits of zeros.
Is any another way to solve this problem.
Thanks in advance.

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