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);

try

{

// 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);

MyStream.Close();

clsConns obj1=new clsConns();

obj1.insertProducts(txtPname.Text,txtCat.Text,int.Parse(txtQty.Text),int.Parse(txtPri.Text),fileData);


}

catch (Exception excep)

{

Response.Write(excep.ToString());


}

}

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.

Hi
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());
             conn.Open();
            SqlCommand cmd = new SqlCommand("insert into test(name,pic) values (@name,@pic)", conn);
            cmd.Parameters.AddWithValue("@name", fup);
            cmd.Parameters.AddWithValue("@pic", pic);
            cmd.ExecuteNonQuery()

Hope this Help

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.